const { useState, useEffect, useRef, useCallback } = React;

/* =========================================================
   TWEAKS — edit-mode defaults
   ========================================================= */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "candy",
  "shape": "rounded",
  "motion": true,
  "hearts": true,
  "kissCursor": true,
  "handle": "@aliceadamswestie",
  "name": "alice",
  "tagline": "just a girl. trying to become a blogger \u2014 softly chaotic, sweetly lethal.",
  "location": "somewhere pink"
}/*EDITMODE-END*/;

/* =========================================================
   LINKS DATA
   ========================================================= */
const LINKS = [
  {
    id: "fanvue",
    label: "Secret Content ;)",
    sub: "the naughty side \u2014 vip only, kiss kiss",
    url: "https://www.fanvue.com/alice_sweets",
    tag: "VIP \u2661",
    cls: "fanvue",
    glyph: (
      <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor">
        <path d="M12 21s-7-4.5-9.3-9.2C1.1 8.4 3.3 4.5 7 4.5c2 0 3.5 1 5 3 1.5-2 3-3 5-3 3.7 0 5.9 3.9 4.3 7.3C19 16.5 12 21 12 21Z"/>
      </svg>
    )
  },
  {
    id: "telegram",
    label: "Telegram",
    sub: "private chat \u2014 me, you, no filter",
    url: "https://t.me/+R4SYghoj-2U4YzVh",
    tag: "NEW \u2728",
    cls: "telegram",
    glyph: (
      <svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor">
        <path d="M21.5 4.2 2.9 11.6c-1 .4-1 1 0 1.3l4.5 1.4 1.7 5.6c.2.7.4.9 1 .3l2.6-2.4 4.7 3.5c.9.5 1.5.2 1.7-.8l3-14.2c.3-1.2-.4-1.7-1.6-1.1Zm-3.7 4-8.2 7.5-.3 3.1-1.2-3.8 9.7-6.8Z"/>
      </svg>
    )
  }
];

/* =========================================================
   AMBIENT HEARTS
   ========================================================= */
function HeartsLayer({ enabled }) {
  const [hearts, setHearts] = useState([]);
  useEffect(() => {
    if (!enabled) { setHearts([]); return; }
    let id = 0;
    const spawn = () => {
      const newH = {
        id: id++,
        x: Math.random() * 100,
        delay: Math.random() * 0.5,
        size: 14 + Math.random() * 22,
        dur: 9 + Math.random() * 8,
        drift: (Math.random() - 0.5) * 80,
        rot: (Math.random() - 0.5) * 30,
        emoji: Math.random() < 0.5 ? "♥" : (Math.random() < 0.5 ? "♡" : "❀"),
        color: Math.random() < 0.5 ? "#ff1f4e" : (Math.random() < 0.5 ? "#ff6ec7" : "#ffd3e1"),
      };
      setHearts((prev) => [...prev.slice(-24), newH]);
    };
    const iv = setInterval(spawn, 650);
    for (let i = 0; i < 6; i++) setTimeout(spawn, i * 200);
    return () => clearInterval(iv);
  }, [enabled]);

  if (!enabled) return null;

  return (
    <div className="ambient" aria-hidden="true">
      {hearts.map(h => (
        <div
          key={h.id}
          className="h"
          style={{
            left: h.x + "%",
            fontSize: h.size,
            color: h.color,
            animationDuration: h.dur + "s",
            animationDelay: h.delay + "s",
            "--r": h.rot + "deg",
            transform: `translateX(${h.drift}px) rotate(${h.rot}deg)`
          }}
        >
          {h.emoji}
        </div>
      ))}
    </div>
  );
}

/* =========================================================
   KISS CURSOR
   ========================================================= */
function KissCursor({ enabled }) {
  const [pos, setPos] = useState({ x: -100, y: -100, visible: false });
  const [marks, setMarks] = useState([]);
  const markId = useRef(0);

  useEffect(() => {
    if (!enabled) return;
    const onMove = (e) => setPos({ x: e.clientX, y: e.clientY, visible: true });
    const onLeave = () => setPos(p => ({ ...p, visible: false }));
    const onClick = (e) => {
      const id = markId.current++;
      const rot = (Math.random() - 0.5) * 30;
      setMarks(prev => [...prev, { id, x: e.clientX, y: e.clientY, rot }]);
      setTimeout(() => setMarks(prev => prev.filter(m => m.id !== id)), 1200);
    };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseleave", onLeave);
    window.addEventListener("click", onClick);
    return () => {
      window.removeEventListener("mousemove", onMove);
      window.removeEventListener("mouseleave", onLeave);
      window.removeEventListener("click", onClick);
    };
  }, [enabled]);

  if (!enabled) return null;

  return (
    <>
      <div
        className={"kiss-cursor" + (pos.visible ? "" : " hidden")}
        style={{ transform: `translate(${pos.x - 10}px, ${pos.y - 14}px) rotate(-18deg)` }}
        aria-hidden="true"
      >💋</div>
      {marks.map(m => (
        <div
          key={m.id}
          className="kiss-mark"
          style={{ left: m.x, top: m.y, "--kr": m.rot + "deg", fontSize: 36 }}
          aria-hidden="true"
        >💋</div>
      ))}
    </>
  );
}

/* =========================================================
   TILT AVATAR CARD
   ========================================================= */
function TiltCard({ children }) {
  const ref = useRef(null);
  const onMove = (e) => {
    const el = ref.current;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width - 0.5;
    const y = (e.clientY - r.top) / r.height - 0.5;
    el.style.transform = `rotateY(${x * 10}deg) rotateX(${-y * 10}deg) translateZ(0)`;
  };
  const onLeave = () => {
    const el = ref.current;
    if (!el) return;
    el.style.transform = "";
  };
  return (
    <div className="profile">
      <div
        className="card enter d2"
        ref={ref}
        onMouseMove={onMove}
        onMouseLeave={onLeave}
      >
        {children}
      </div>
    </div>
  );
}

/* =========================================================
   PLACEHOLDER AVATAR
   ========================================================= */
function PlaceholderAvatar({ name }) {
  // Real photo now
  return (
    <img src="alice.png" alt="alice" style={{position:'absolute',inset:0,width:'100%',height:'100%',objectFit:'cover'}} />
  );
}
function _UnusedPlaceholderAvatar({ name }) {
  const initials = (name || "A").trim().slice(0, 1).toUpperCase();
  return (
    <>
      <div className="ph-bg" />
      <svg className="ph" viewBox="0 0 300 375" preserveAspectRatio="none" aria-hidden="true">
        <defs>
          <linearGradient id="hair" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="#d9582a"/>
            <stop offset="1" stopColor="#9a2b0d"/>
          </linearGradient>
          <radialGradient id="blush" cx=".5" cy=".5" r=".5">
            <stop offset="0" stopColor="#ff5577" stopOpacity=".7"/>
            <stop offset="1" stopColor="#ff5577" stopOpacity="0"/>
          </radialGradient>
        </defs>
        {/* face silhouette */}
        <ellipse cx="150" cy="175" rx="80" ry="92" fill="#ffd9c0" />
        {/* hair */}
        <path d="M70 150 Q80 60 150 55 Q220 60 230 150 Q230 115 190 100 Q160 92 150 105 Q140 92 110 100 Q70 115 70 150 Z" fill="url(#hair)"/>
        <path d="M230 150 Q235 230 215 290 L245 305 Q260 230 245 150 Z" fill="url(#hair)"/>
        <path d="M70 150 Q65 230 85 290 L55 305 Q40 230 55 150 Z" fill="url(#hair)"/>
        {/* bangs */}
        <path d="M95 120 Q130 155 150 150 Q170 155 205 120 Q200 145 170 160 Q150 165 130 160 Q100 145 95 120 Z" fill="url(#hair)"/>
        {/* eyes */}
        <ellipse cx="125" cy="180" rx="5" ry="6" fill="#3a1c08"/>
        <ellipse cx="175" cy="180" rx="5" ry="6" fill="#3a1c08"/>
        <path d="M115 170 Q125 165 135 170" stroke="#3a1c08" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        <path d="M165 170 Q175 165 185 170" stroke="#3a1c08" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        {/* blush */}
        <ellipse cx="115" cy="210" rx="16" ry="8" fill="url(#blush)"/>
        <ellipse cx="185" cy="210" rx="16" ry="8" fill="url(#blush)"/>
        {/* lips */}
        <path d="M135 235 Q150 248 165 235 Q160 232 150 236 Q140 232 135 235 Z" fill="#d41a3a"/>
        {/* neck + shoulders */}
        <path d="M120 255 Q150 275 180 255 L180 285 Q150 295 120 285 Z" fill="#ffd9c0"/>
        <path d="M50 375 Q60 310 120 290 Q150 305 180 290 Q240 310 250 375 Z" fill="#1a1a1a"/>
        {/* bow */}
        <path d="M140 100 Q150 90 160 100 Q170 92 170 102 Q160 105 160 100 Q150 110 140 100 Q130 102 130 92 Q140 92 140 100 Z" fill="#ff1f4e"/>
      </svg>
      <div className="ph-drop">placeholder portrait —<br/><em>drop your photo here</em></div>
    </>
  );
}

/* =========================================================
   TWEAKS PANEL
   ========================================================= */
function TweaksPanel({ open, state, setState }) {
  if (!open) return null;
  const set = (k, v) => setState(prev => ({ ...prev, [k]: v }));
  return (
    <div className="tweaks-panel">
      <h4>Tw<em>e</em>aks</h4>

      <div className="row">
        <label>Theme</label>
        <div className="swatches">
          {[
            { k: "candy",  c: "linear-gradient(135deg,#ff6ec7,#ff1f4e)" },
            { k: "cherry", c: "linear-gradient(135deg,#ff4572,#c9002f)" },
            { k: "chrome", c: "linear-gradient(135deg,#ff9bd1,#dcdcdc)" },
          ].map(s => (
            <div
              key={s.k}
              className={"sw" + (state.theme === s.k ? " active" : "")}
              style={{ background: s.c }}
              onClick={() => set("theme", s.k)}
              title={s.k}
            />
          ))}
        </div>
      </div>

      <div className="row">
        <label>Button shape</label>
        <div className="seg">
          {["rounded","pill","square"].map(s => (
            <button key={s} className={state.shape === s ? "on" : ""} onClick={() => set("shape", s)}>{s}</button>
          ))}
        </div>
      </div>

      <div className="row">
        <label>Entry + hover motion</label>
        <div className={"switch" + (state.motion ? " on" : "")} onClick={() => set("motion", !state.motion)} />
      </div>

      <div className="row">
        <label>Floating hearts</label>
        <div className={"switch" + (state.hearts ? " on" : "")} onClick={() => set("hearts", !state.hearts)} />
      </div>

      <div className="row">
        <label>Kiss cursor</label>
        <div className={"switch" + (state.kissCursor ? " on" : "")} onClick={() => set("kissCursor", !state.kissCursor)} />
      </div>
    </div>
  );
}

/* =========================================================
   APP
   ========================================================= */
function App() {
  const [tw, setTw] = useState(TWEAK_DEFAULTS);
  const [panelOpen, setPanelOpen] = useState(false);
  const [stats, setStats] = useState({ tiktok: "14.8K", fanvue: "VIP", telegram: "3.2K" });

  // edit-mode bridge
  useEffect(() => {
    const onMsg = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setPanelOpen(true);
      if (d.type === "__deactivate_edit_mode") setPanelOpen(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({ type: "__edit_mode_available" }, "*"); } catch {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  // persist to host
  useEffect(() => {
    try { window.parent.postMessage({ type: "__edit_mode_set_keys", edits: tw }, "*"); } catch {}
  }, [tw]);

  // apply theme + shape to body
  useEffect(() => {
    document.body.classList.toggle("theme-candy", tw.theme === "candy");
    document.body.classList.toggle("theme-cherry", tw.theme === "cherry");
    document.body.classList.toggle("theme-chrome", tw.theme === "chrome");
    document.body.classList.toggle("shape-pill", tw.shape === "pill");
    document.body.classList.toggle("shape-square", tw.shape === "square");
    document.body.classList.toggle("no-motion", !tw.motion);
  }, [tw.theme, tw.shape, tw.motion]);

  const setKey = (k, v) => setTw(prev => ({ ...prev, [k]: v }));

  return (
    <>
      <HeartsLayer enabled={tw.hearts && tw.motion} />
      <KissCursor enabled={tw.kissCursor && tw.motion} />

      <div className="page">
        <div className="topbar enter d1">
          <div className="logo">alice&apos;s little <em>black book</em></div>
          <button className="share" onClick={() => {
            if (navigator.share) navigator.share({ title:"alice", url: location.href }).catch(()=>{});
            else navigator.clipboard?.writeText(location.href);
          }}>
            ⇪ share
          </button>
        </div>

        <div className="ribbon enter d1" aria-hidden="true">
          <div className="track">
            {Array.from({ length: 2 }).map((_, i) => (
              <span key={i}>
                <span>new drop every friday</span>
                <span className="star">✦</span>
                <span>kiss kiss, don&apos;t tell</span>
                <span className="star">✦</span>
                <span>link in bio &mdash; obviously</span>
                <span className="star">✦</span>
                <span>soft girl, sharp edges</span>
                <span className="star">✦</span>
              </span>
            ))}
          </div>
        </div>

        <div className="stage">
          {/* LEFT — avatar card */}
          <TiltCard>
            <div className="tape tl">hi it&apos;s me ✿</div>
            <div className="photo">
              <PlaceholderAvatar name={tw.name} />
            </div>
            <div className="verified" title="verified cutie">♥</div>
            <div className="heart-badge" aria-hidden="true">
              <svg width="64" height="64" viewBox="0 0 64 64">
                <path d="M32 56s-22-12-22-28c0-8 6-14 14-14 4 0 7 2 8 4 1-2 4-4 8-4 8 0 14 6 14 14 0 16-22 28-22 28Z"
                      fill="#ff1f4e" stroke="#000" strokeWidth="3" strokeLinejoin="round"/>
                <text x="32" y="36" textAnchor="middle" fontFamily="Bagel Fat One" fontSize="11" fill="#fff4ea">xoxo</text>
              </svg>
            </div>
            <div className="tape br">♥ 2.8k babes</div>
            <div className="handle-pill">{tw.handle}</div>
          </TiltCard>

          {/* RIGHT — hero + links */}
          <div>
            <div className="hero">
              <div className="kicker enter d1"><span className="dot" /> online now &middot; sending kisses</div>
              <h1 className="enter d2">
                hi, i&apos;m <span className="it">{tw.name}</span><br/>
                <span className="stroke">kiss</span><span> &amp; tell</span>
              </h1>
              <p className="tag enter d3">
                {tw.tagline} <span className="kiss">xo</span>
              </p>

              <div className="meta enter d3">
                <span className="chip"><b>19</b> yo</span>
                <span className="chip">📍 {tw.location}</span>
                <span className="chip"><b>2.8k</b> babes</span>
                <span className="chip"><span className="sparkle">✦</span> creator</span>
              </div>
            </div>

            <div className="section-label enter d4">pick your poison <span className="sparkle">✦</span></div>

            <div className="links">
              {LINKS.map((l, i) => (
                <a
                  key={l.id}
                  className={`link ${l.cls} enter d${5 + i}`}
                  href={l.url}
                  target="_blank"
                  rel="noreferrer"
                  style={{ "--rot": `${[-1.2, 1.4, -0.8, 0.6][i] || 0}deg` }}
                >
                  {l.tag && <span className="tag-tiny">{l.tag}</span>}
                  <span className="glyph">{l.glyph}</span>
                  <span className="body">
                    <span className="label">{l.label}</span>
                    <span className="sub"><span className="pin" /> {l.sub}</span>
                  </span>
                  <span className="arrow">→</span>
                  <span className="peel" />
                </a>
              ))}
            </div>

            <div className="footer enter d8">
              made with <em>love</em> &amp; lipstick &middot; © {new Date().getFullYear()} alice
            </div>
          </div>
        </div>
      </div>

      <TweaksPanel open={panelOpen} state={tw} setState={setTw} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
