/* eslint-disable */
/* AIStylist — quiz → contact capture → curated picks → AI chat with memory. */
const QUIZ = [
  {
    q: "Who are we styling for?",
    sub: "We'll tailor the picks.",
    opts: [
      { id: "women",    label: "Womens",       sub: "Shop the womens line" },
      { id: "men",      label: "Mens",         sub: "Shop the mens line" },
      { id: "kids",     label: "Kids",         sub: "Apparel — tees, hoodies, sweats" },
      { id: "gift_her", label: "Gift for her", sub: "Partner, mom, friend" },
      { id: "gift_him", label: "Gift for him", sub: "Partner, dad, friend" },
    ],
  },
  {
    q: "What kind of pieces?", sub: "Pick anything you're into.", multi: true,
    opts: [
      { id: "necklaces", label: "Necklaces", sub: "Chains + pendants" },
      { id: "bracelets", label: "Bracelets", sub: "Cuffs + tennis" },
      { id: "rings",     label: "Rings",     sub: "Stacking + signet" },
      { id: "earrings",  label: "Earrings",  sub: "Hoops + studs" },
      { id: "anklets",   label: "Anklets",   sub: "Delicate + chain" },
      { id: "apparel",   label: "Apparel",   sub: "Tees + caps" },
    ],
  },
  {
    q: "What's your vibe?", sub: "Pick all that feel right.", multi: true,
    opts: [
      { id: "minimal",  label: "Minimal",   sub: "Quiet, clean" },
      { id: "layered",  label: "Layered",   sub: "Stacked + styled" },
      { id: "statement",label: "Statement", sub: "Bold pieces" },
      { id: "vintage",  label: "Vintage",   sub: "Heirloom feel" },
      { id: "edgy",     label: "Edgy",      sub: "Cool girl" },
      { id: "everyday", label: "Everyday",  sub: "Wears with anything" },
    ],
  },
  {
    q: "Which metals do you wear?", multi: true,
    opts: [
      { id: "gold",   label: "Gold",       sub: "Warm + classic" },
      { id: "silver", label: "Silver",     sub: "Cool + modern" },
      { id: "rose",   label: "Rose gold",  sub: "Soft + warm" },
      { id: "mixed",  label: "Mixed",      sub: "All of the above" },
    ],
  },
  {
    q: "When will you wear it?", sub: "We'll match the energy.", multi: true,
    opts: [
      { id: "daily",  label: "Daily wear", sub: "Never take off" },
      { id: "work",   label: "Work / pro", sub: "Polished, subtle" },
      { id: "going",  label: "Going out",  sub: "Dinner, dates, drinks" },
      { id: "events", label: "Events",     sub: "Weddings, occasions" },
      { id: "travel", label: "Travel",     sub: "Waterproof, easy" },
    ],
  },
];

// Mock fallback when Shopify isn't configured / fetch fails.
const MOCK_PICKS = [
  { id: "p1", handle: "cameo-drop", name: "Cameo Drop Necklace", price: 78,  badge: "BESTSELLER", img: "assets/hero-necklaces.jpg",  why: "Layers beautifully with shorter chains.",  tags: ["Necklaces","Gold","Women","Waterproof","Pendant"] },
  { id: "p2", handle: "amelia-signet", name: "Amelia Signet Ring",  price: 124, img: "assets/product-amelia-ring.jpg", why: "Vintage feel, modern weight.",            tags: ["Rings","Gold","Women","Statement"] },
  { id: "p3", handle: "sienna-set", name: "Sienna Layered Set",  price: 168, badge: "SET",         img: "assets/hero-main.jpg",          why: "Three chains, pre-styled to layer.",     tags: ["Necklaces","Gold","Women","Charm"] },
  { id: "p4", handle: "ines-pearl-drops", name: "Ines Pearl Drops", price: 64, img: "assets/banner-bundles.jpg", why: "The everyday earring you'll never take off.", tags: ["Earrings","Gold","Women","Drops"] },
];

// Quiz-answer → product-tag maps. Used by scorePicks() against live catalog.
const PIECE_CATEGORY = { necklaces: "Necklaces", bracelets: "Bracelets", rings: "Rings", earrings: "Earrings", anklets: "Anklet", apparel: "Apparel" };
const WHO_GENDER     = { women: "Women", men: "Men", kids: "Kids", gift_her: "Women", gift_him: "Men" };
const METAL_TAG      = { gold: "Gold", silver: "Silver", rose: "Rose Gold" };
const VIBE_SUBCAT    = { layered: ["Charm","Chain"], statement: ["Statement","Cuff","Cuban"], vintage: ["Pendant","Signet"], edgy: ["Cuban","Snake","Curb"], minimal: ["Studs","Band","Huggies"], everyday: ["Hoops","Band","Chain","Studs"] };

function whyFor(p, answers) {
  const tags = new Set(p.tags || []);
  if (tags.has("Pearl"))    return "Soft pearl detail — wears with everything.";
  if (tags.has("Cuban"))    return "Heavy Cuban link, built for everyday wear.";
  if (tags.has("Pendant"))  return "Pendant that layers with shorter chains.";
  if (tags.has("Signet"))   return "Signet weight with a vintage edge.";
  if (tags.has("Hoops"))    return "Everyday hoop you'll never take off.";
  if (tags.has("Studs"))    return "Quiet stud — pairs with anything.";
  if (tags.has("Huggies"))  return "Huggie-fit, locks on and stays put.";
  if (tags.has("Drops"))    return "Drops that catch the light.";
  if (tags.has("Band"))     return "Slim band, stacks effortlessly.";
  if (tags.has("Stacking")) return "Made to layer with the rest of your set.";
  if (tags.has("Charm"))    return "Charm detail makes it feel collected.";
  if (tags.has("Chain"))    return "Foundational chain — start of a layer.";
  return "Picked for the vibe you described.";
}

function scorePicks(catalog, answers) {
  if (!catalog || catalog.length === 0) return [];
  const who    = answers[0];
  const pieces = answers[1] || [];
  const vibes  = answers[2] || [];
  const metals = answers[3] || [];
  const targetGender = WHO_GENDER[who];
  const targetCats   = pieces.map(p => PIECE_CATEGORY[p]).filter(Boolean);
  const targetMetals = metals.includes("mixed") ? null : metals.map(m => METAL_TAG[m]).filter(Boolean);
  const vibeSubcats  = new Set(vibes.flatMap(v => VIBE_SUBCAT[v] || []));

  const scored = catalog.map(p => {
    const tags = new Set(p.tags || []);
    let score = 0;
    // Hard-ish gates
    if (targetGender && !tags.has(targetGender)) score -= 100;
    if (targetCats.length && !targetCats.some(c => tags.has(c))) score -= 100;
    if (targetMetals && targetMetals.length && !targetMetals.some(m => tags.has(m))) score -= 50;
    // Bonuses
    if (tags.has("Bestseller")) score += 5;
    if (tags.has("New")) score += 2;
    [...vibeSubcats].forEach(s => { if (tags.has(s)) score += 4; });
    if (tags.has("Waterproof")) score += 1;
    return { p, score };
  })
  .filter(x => x.score >= 0)
  .sort((a, b) => b.score - a.score);

  // Spread across selected categories so a multi-piece pick doesn't all
  // collapse to one category (e.g. 4 hoops if you said "earrings + rings")
  const out = [];
  if (targetCats.length > 1) {
    const buckets = Object.fromEntries(targetCats.map(c => [c, []]));
    scored.forEach(({ p }) => {
      const cat = targetCats.find(c => (p.tags || []).includes(c));
      if (cat && buckets[cat].length < 2) buckets[cat].push(p);
    });
    targetCats.forEach(c => out.push(...buckets[c]));
  } else {
    scored.slice(0, 4).forEach(x => out.push(x.p));
  }
  return out.slice(0, 4);
}

const SUGGEST = {
  initial: ["Layered set under $150", "Gift for mom", "Daily wear, gold", "Waterproof?"],
  refine:  ["Cheaper", "Bolder", "Gold only", "Show more"],
};

function AIStylist({ open, onClose, onAdd, onView }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [thinking, setThinking] = React.useState(false);
  const [contact, setContact] = React.useState({ email: "", phone: "", smsOk: true });
  const [chat, setChat] = React.useState([]);
  const [chatInput, setChatInput] = React.useState("");
  const [aiTyping, setAiTyping] = React.useState(false);
  const [catalog, setCatalog] = React.useState(null);
  const [picks, setPicks] = React.useState(MOCK_PICKS);
  const feedRef = React.useRef(null);

  React.useEffect(() => { if (open) { setStep(0); setAnswers({}); setChat([]); setChatInput(""); setPicks(MOCK_PICKS); } }, [open]);

  // Lazily fetch the full catalog once the stylist opens — re-used for picks
  // scoring + chat refinement so we never lean on the mock fallback.
  React.useEffect(() => {
    if (!open || catalog) return;
    let cancelled = false;
    (async () => {
      try {
        if (window.Shopify?.isConfigured?.()) {
          const c = await window.Shopify.getCollection("shop-all");
          if (!cancelled && c?.products) setCatalog(c.products);
        }
      } catch (e) { /* keep mock fallback */ }
    })();
    return () => { cancelled = true; };
  }, [open, catalog]);
  React.useEffect(() => { if (feedRef.current) feedRef.current.scrollTop = feedRef.current.scrollHeight; }, [chat, aiTyping]);

  if (!open) return null;
  const current = typeof step === "number" ? QUIZ[step] : null;

  const onPick = (optId) => {
    if (current.multi) {
      const cur = answers[step] || [];
      const next = cur.includes(optId) ? cur.filter(x => x !== optId) : [...cur, optId];
      setAnswers({ ...answers, [step]: next });
      clearTimeout(window.__aiQuizAdvance);
      if (next.length > 0) window.__aiQuizAdvance = setTimeout(() => goNext(step), 1600);
    } else {
      setAnswers({ ...answers, [step]: optId });
      setTimeout(() => goNext(step), 280);
    }
  };
  const goNext = (idx) => { if (idx < QUIZ.length - 1) setStep(idx + 1); else setStep("capture"); };
  const computePicks = () => {
    const scored = scorePicks(catalog || [], answers);
    if (scored.length > 0) {
      const mapped = scored.map(p => ({
        id: p.id || p.handle,
        handle: p.handle,
        name: p.name || p.title,
        price: p.price,
        badge: p.badge,
        img: p.img || p.featuredImage?.url || "assets/hero-main.jpg",
        why: whyFor(p, answers),
        tags: p.tags || [],
      }));
      setPicks(mapped);
    } else {
      setPicks(MOCK_PICKS);
    }
  };
  const submitContact = (e) => {
    e?.preventDefault();
    if (window.dropIdentify) window.dropIdentify({ email: contact.email, phone_number: contact.phone, $consent: contact.smsOk ? ["email","sms"] : ["email"] });
    if (window.dropTrack) window.dropTrack("stylist_capture", { has_phone: !!contact.phone, has_email: !!contact.email });
    setThinking(true); setStep("thinking");
    setTimeout(() => { computePicks(); setThinking(false); setStep("results"); if (window.dropTrack) window.dropTrack("stylist_quiz_complete", { answers }); }, 1400);
  };
  const skipCapture = () => { setThinking(true); setStep("thinking"); setTimeout(() => { computePicks(); setThinking(false); setStep("results"); }, 1000); };
  const restart = () => { setStep(0); setAnswers({}); };

  const openChat = () => {
    setStep("chat");
    if (chat.length === 0) {
      const summary = summarizeAnswers(answers);
      setChat([{ from: "ai", text: summary
        ? `I've got your edit above${summary}. Want me to refine, or anything else? Try a vibe, occasion, or budget.`
        : "Hey — tell me what you're shopping for. Vibe, occasion, person, budget — anything works.",
        suggests: SUGGEST.refine }]);
    }
  };

  const sendChat = async (textOverride) => {
    const text = (textOverride ?? chatInput).trim();
    if (!text) return;
    const newUser = { from: "user", text };
    setChat(c => [...c, newUser]);
    setChatInput("");
    setAiTyping(true);

    const history = [...chat, newUser].slice(-8).map(m => `${m.from === "user" ? "Customer" : "Stylist"}: ${m.text}`).join("\n");
    const chatCatalog = picks.map(p => `${p.id} | ${p.name} | $${p.price}${p.badge ? ` · ${p.badge}` : ""} | ${p.why} | tags: ${(p.tags || []).join(",")}`).join("\n");
    const profile = summarizeAnswers(answers) || "no quiz answers yet";
    const sys = `You are the DROP Jewelry stylist. DROP makes affordable (under $200), waterproof, hypoallergenic, tarnish-free jewelry across the women's and men's lines. The kids' line is apparel-only (tees, hoodies, sweatpants). Free shipping over $75, 30-day returns.
Be warm, concise (2 short sentences MAX), confident. No emojis. Sound like a stylish friend, not a chatbot.
After your reply, on a new line, output: PICKS: id1,id2 (1-3 ids from catalog) or PICKS: none.

CATALOG:
${chatCatalog}

CUSTOMER PROFILE: ${profile}

CONVERSATION:
${history}`;

    let reply = null, pickIds = [];

    // Production path: Vercel Function proxy to Anthropic. Falls back to
    // window.claude.complete (Claude Code dev preview only) then to the
    // generic suggestion. The system prompt is the brand-voice + catalog
    // context; the user message is just the latest customer turn — the
    // history is rendered into the system prompt so context follows.
    const userMessages = [...chat, newUser]
      .filter(m => m.from === "user")
      .slice(-6)
      .map(m => ({ role: "user", content: m.text }));

    try {
      const r = await fetch("/api/stylist", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          system: sys,
          messages: userMessages.length ? userMessages : [{ role: "user", content: text }],
        }),
      });
      if (r.ok) {
        const data = await r.json();
        if (data.reply) {
          const m = String(data.reply).match(/^([\s\S]*?)\n*PICKS:\s*(.*)$/i);
          if (m) {
            reply = m[1].trim();
            const ids = m[2].trim();
            if (ids && !/^none/i.test(ids)) pickIds = ids.split(/[,\s]+/).filter(Boolean);
          } else {
            reply = String(data.reply).trim();
          }
        }
      }
    } catch (e) { /* fall through to dev-preview path */ }

    if (!reply) {
      try {
        if (window.claude && window.claude.complete) {
          const resp = await window.claude.complete({ messages: [{ role: "user", content: sys }] });
          const m = String(resp || "").match(/^([\s\S]*?)\n*PICKS:\s*(.*)$/i);
          if (m) {
            reply = m[1].trim();
            const ids = m[2].trim();
            if (ids && !/^none/i.test(ids)) pickIds = ids.split(/[,\s]+/).filter(Boolean);
          } else { reply = String(resp).trim(); }
        }
      } catch (e) { /* final fallback */ }
    }

    setAiTyping(false);
    if (reply) {
      const refined = pickIds.map(id => picks.find(p => p.id === id)).filter(Boolean);
      setChat(c => [...c, { from: "ai", text: reply, picks: refined.length ? refined : null, suggests: SUGGEST.refine }]);
    } else {
      setChat(c => [...c, { from: "ai", text: "Here are a few that might match. Want me to go cheaper, bolder, or focus on a metal?", picks: picks.slice(0, 3), suggests: SUGGEST.refine }]);
    }
  };

  const progress = typeof step === "number" ? ((step + 1) / QUIZ.length) * 100 : 100;

  return (
    <div className="ai-scrim" onClick={onClose}>
      <aside className="ai" onClick={e => e.stopPropagation()}>
        <header className="ai-head">
          <div className="ai-brand">
            <span className="ai-dot"></span>
            <div>
              <div className="ai-title">DROP Stylist</div>
              <div className="ai-sub">Powered by AI · Replies instantly</div>
            </div>
            <span className="ai-tag">Beta</span>
          </div>
          <button className="ai-close" onClick={onClose} aria-label="Close">×</button>
        </header>

        {typeof step === "number" && <div className="ai-progress"><div className="ai-progress-fill" style={{width: progress + "%"}}></div></div>}

        {typeof step === "number" && !thinking && (
          <div className="ai-body">
            <div className="ai-step-num">Step {step + 1} of {QUIZ.length}</div>
            <h2 className="ai-q">{current.q}</h2>
            {current.sub && <p className="ai-qs">{current.sub}</p>}
            <div className="ai-opts">
              {current.opts.map(o => {
                const active = current.multi ? (answers[step] || []).includes(o.id) : answers[step] === o.id;
                return (
                  <button key={o.id} className={"ai-opt " + (active ? "active" : "")} onClick={() => onPick(o.id)}>
                    <span className="ai-opt-l">{o.label}</span>
                    {o.sub && <span className="ai-opt-s">{o.sub}</span>}
                    {active && <span className="ai-check">✓</span>}
                  </button>
                );
              })}
            </div>
            {current.multi && <p className="ai-multi-hint">{answers[step]?.length ? `${answers[step].length} selected · advancing in a moment…` : "Pick any that apply — we'll auto-advance."}</p>}
            <button className="ai-skip" onClick={openChat}>Skip — chat with the stylist instead</button>
          </div>
        )}

        {step === "capture" && (
          <div className="ai-body ai-capture">
            <div className="ai-step-num">Almost there</div>
            <h2 className="ai-q">Save your edit.</h2>
            <p className="ai-qs">We'll text + email your picks plus <strong>20% off</strong> your first order.</p>
            <form className="ai-cap-form" onSubmit={submitContact}>
              <label className="ai-cap-field"><span className="ai-cap-l">Email</span>
                <input type="email" required placeholder="you@email.com" value={contact.email} onChange={e => setContact({...contact, email: e.target.value})} /></label>
              <label className="ai-cap-field"><span className="ai-cap-l">Phone <span className="ai-cap-opt">(SMS — recommended)</span></span>
                <div className="ai-cap-phone"><span className="ai-flag">🇺🇸 +1</span>
                  <input type="tel" placeholder="(555) 123-4567" value={contact.phone} onChange={e => setContact({...contact, phone: e.target.value})} /></div></label>
              <label className="ai-cap-check"><input type="checkbox" checked={contact.smsOk} onChange={e => setContact({...contact, smsOk: e.target.checked})} />
                <span>Text me my picks + early access to drops. Reply STOP to opt out.</span></label>
              <button className="btn-primary btn-block" type="submit">SHOW MY PICKS →</button>
              <button type="button" className="ai-skip" onClick={skipCapture}>Skip — just show me</button>
              <p className="ai-cap-fine">By submitting, you agree to receive marketing emails and texts. Msg & data rates may apply.</p>
            </form>
          </div>
        )}

        {thinking && (
          <div className="ai-thinking">
            <div className="ai-pulse"></div>
            <div className="ai-thinking-text">Curating your picks…</div>
            <div className="ai-thinking-sub">Reading 1,247 pieces against your vibe.</div>
          </div>
        )}

        {step === "results" && (
          <div className="ai-results">
            <div className="ai-results-head">
              <div><div className="eyebrow">YOUR EDIT</div><h2 className="ai-results-h">{picks.length} {picks.length === 1 ? "piece" : "pieces"}, picked for you.</h2></div>
              <button className="ai-restart" onClick={restart}>Retake quiz</button>
            </div>
            <div className="ai-picks">
              {picks.map(p => (
                <div key={p.id} className="ai-pick">
                  <div className="ai-pick-img" style={{backgroundImage:`url(${p.img})`}}>{p.badge && <span className="ai-pick-badge">{p.badge}</span>}</div>
                  <div className="ai-pick-meta">
                    <div className="ai-pick-name">{p.name}</div>
                    <div className="ai-pick-price">${p.price}</div>
                    <div className="ai-pick-why"><strong>Why:</strong> {p.why}</div>
                    <div className="ai-pick-actions">
                      <button className="btn-primary ai-pick-add" onClick={() => onAdd(p, 1)}>ADD</button>
                      <button className="btn-link" onClick={() => p.handle ? (window.location.href = "product.html?handle=" + p.handle) : onView(p)}>Details →</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <button className="ai-chat-cta" onClick={openChat}><span className="ai-dot"></span> Refine with the stylist</button>
          </div>
        )}

        {step === "chat" && (
          <div className="ai-chat">
            <div className="ai-chat-feed" ref={feedRef}>
              {chat.length === 0 && (
                <div className="ai-chat-welcome">
                  <div className="ai-pulse-sm"></div>
                  <h3 className="ai-welcome-h">Hi, I'm your DROP Stylist.</h3>
                  <p className="ai-welcome-p">Tell me what you're shopping for — vibe, occasion, person, or vague vibes work too.</p>
                  <div className="ai-welcome-chips">{SUGGEST.initial.map(s => <button key={s} className="ai-suggest" onClick={() => sendChat(s)}>{s}</button>)}</div>
                </div>
              )}
              {chat.map((m, i) => (
                <div key={i} className={"ai-msg ai-msg-" + m.from}>
                  {m.from === "ai" && <span className="ai-avatar"><span className="ai-dot"></span></span>}
                  <div className="ai-msg-content">
                    <div className="ai-bubble">{m.text}</div>
                    {m.picks && (
                      <div className="ai-msg-picks">
                        {m.picks.map(p => (
                          <a key={p.id} className="ai-msg-pick" onClick={() => onView(p)}>
                            <div className="ai-msg-pick-img" style={{backgroundImage:`url(${p.img})`}}>{p.badge && <span className="ai-msg-pick-badge">{p.badge}</span>}</div>
                            <div className="ai-msg-pick-body">
                              <div className="ai-msg-pick-name">{p.name}</div>
                              <div className="ai-msg-pick-bottom">
                                <span className="ai-msg-pick-price">${p.price}</span>
                                <button className="ai-msg-pick-add" onClick={(e) => { e.stopPropagation(); onAdd(p, 1); }}>+ Add</button>
                              </div>
                            </div>
                          </a>
                        ))}
                      </div>
                    )}
                    {m.suggests && i === chat.length - 1 && !aiTyping && (
                      <div className="ai-msg-suggests">{m.suggests.map(s => <button key={s} className="ai-suggest ai-suggest-sm" onClick={() => sendChat(s)}>{s}</button>)}</div>
                    )}
                  </div>
                </div>
              ))}
              {aiTyping && (
                <div className="ai-msg ai-msg-ai">
                  <span className="ai-avatar"><span className="ai-dot"></span></span>
                  <div className="ai-msg-content"><div className="ai-bubble ai-typing"><span></span><span></span><span></span></div></div>
                </div>
              )}
            </div>
            <form className="ai-chat-input" onSubmit={(e) => { e.preventDefault(); sendChat(); }}>
              <input placeholder="Ask anything — gift ideas, sizing, styling…" value={chatInput} onChange={e => setChatInput(e.target.value)}
                onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendChat(); } }} />
              <button type="submit" aria-label="Send" onClick={(e) => { e.preventDefault(); sendChat(); }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{pointerEvents:"none"}}><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>
              </button>
            </form>
            <div className="ai-chat-foot">Replies are AI-generated. Free returns + 30 days to decide.</div>
          </div>
        )}
      </aside>
    </div>
  );
}

function summarizeAnswers(a) {
  const parts = [];
  Object.entries(a).forEach(([idx, val]) => {
    const q = QUIZ[idx]; if (!q) return;
    const labels = (Array.isArray(val) ? val : [val]).map(id => q.opts.find(o => o.id === id)?.label).filter(Boolean);
    if (labels.length) parts.push(labels.join("/"));
  });
  return parts.length ? ` (${parts.join(" · ")})` : "";
}
window.AIStylist = AIStylist;
