/* support.jsx, customer support, agent-first.
   SupportFlow: hub (Ask Yoshi + browse topics + talk to a person) →
   topic detail (accordion FAQ) → specialist live chat. Opened as an
   overlay from Profile, same push-enter vocabulary as TransferFlow. */

const SUPPORT_TOPICS = [
  { id: "disputes", icon: "shield", name: "Disputes & fraud", sub: "Unauthorized charges, chargebacks",
    qs: [
      ["I see a charge I don't recognize", "Open the charge in your stream and tap Dispute. Yoshi freezes the card, files the claim, and issues a provisional credit within one business day while we investigate. You don't pay for fraud you report."],
      ["My card was lost or stolen", "Freeze it instantly from Accounts → Card, then tap Replace. A virtual card is live in seconds so nothing breaks; the physical replacement ships in 3–5 days."],
      ["How long do disputes take?", "Provisional credit lands within 1 business day. A final decision follows within 10 business days for most card disputes, up to 45 for complex cases. We'll keep you posted in your stream."],
    ] },
  { id: "transfers", icon: "swap", name: "Transfers & deposits", sub: "ACH, wires, holds, limits",
    qs: [
      ["Why is my deposit on hold?", "New external deposits can hold 1–2 business days while the funds clear. Instant transfers and Yoshi-to-Yoshi moves are available right away. You'll see the release date on the transfer."],
      ["What are my transfer limits?", "Standard ACH is up to $25,000 per day. Wires and instant transfers have their own limits, shown before you confirm. Need more for a one-time move? A specialist can raise it after a quick check."],
      ["I sent money to the wrong place", "If it hasn't settled, Yoshi can often cancel it, open the transfer and tap Cancel. If it's already out, message a specialist and we'll start a recall."],
    ] },
  { id: "cards", icon: "card", name: "Cards", sub: "Activate, freeze, replace",
    qs: [
      ["How do I activate my card?", "Go to Accounts → Card and tap Activate. Your virtual card works online immediately; the physical card activates the same way once it arrives."],
      ["Can my agent use the card?", "Yes, issue Yoshi a virtual card scoped to a monthly cap and a set of merchants. It runs as a standing rule inside your trust ladder, and you can freeze it anytime."],
      ["How do rewards work?", "Rewards accrue automatically on eligible spend and post monthly to Checking. See the running total in Accounts → Card → Rewards."],
    ] },
  { id: "account", icon: "profile", name: "Account & KYC", sub: "Verification, limits, statements",
    qs: [
      ["My verification is stuck", "Most KYC checks clear in minutes. If yours is pending more than an hour, message a specialist, usually it's a quick document re-upload."],
      ["How do I close my account?", "We'd hate to see you go. A specialist can walk you through moving out your balance and closing cleanly, your statements and tax docs stay available after."],
    ] },
  { id: "tax", icon: "doc", name: "Statements & tax", sub: "1099s, cost basis, reports",
    qs: [
      ["Where are my tax documents?", "Open Documents from your profile, 1099-B, 1099-INT and crypto forms post there as they're ready, alongside every monthly statement."],
      ["My cost basis looks wrong", "Tell Yoshi which lot looks off and it'll reconcile against your trade history. If a transfer-in is missing a basis, a specialist can adjust it."],
      ["Can I get a custom report?", "Yes, ask Yoshi for it in plain words (\"realized gains for Q2\", \"all interest earned this year\") and it builds a PDF you can download or send to your accountant."],
    ] },
];

const supportReply = (text) => {
  const t = text.toLowerCase();
  if (/(fraud|stolen|unauthor|didn't make|scam)/.test(t)) return "I've got you. I'm freezing the affected card now and opening a dispute, you'll see a provisional credit within one business day. Can you confirm the merchant name on the charge?";
  if (/(freeze|lost|missing card)/.test(t)) return "Done, I've frozen the card so nothing else can post. Want me to ship a replacement, or just unfreeze once you find it?";
  if (/(transfer|deposit|hold|wire|ach)/.test(t)) return "Let me pull up that transfer. I can see the hold release date and, if it hasn't settled, cancel or expedite it. Which transfer is it, the one to Checking today?";
  if (/(limit|raise|increase)/.test(t)) return "I can request a higher limit for you. For a one-time move I'll just need the amount and where it's going; standing increases take a quick review.";
  if (/(thank|thanks|great|perfect|appreciate)/.test(t)) return "Anytime. I'll leave the dispute open in your stream so you can follow along. Anything else while I'm here?";
  return "Thanks, I've pulled up your account and I'm looking now. Give me one moment and I'll come back with something concrete.";
};

const SUPPORT_SEED = [
  { from: "sys", t: "You're chatting with Fin, Yoshi's third-party support assistant. Fin can see your account but not your card number or password." },
  { from: "agent", t: "Hi Rivka, I'm Fin — Yoshi's support assistant. What can I help you sort out today?", time: "now" },
];

const SupportFlow = ({ onClose, nav }) => {
  const [screen, setScreen] = useState("chat");          // routes straight to Fin (3rd-party)
  const [topic, setTopic] = useState(null);

  const askYoshi = () => {
    onClose();
    nav.ask(
      "I need a hand with something on my account.",
      "Of course, I can see your accounts, cards, and recent activity, so tell me what's going on and I'll fix it or walk you through it. If it needs a human, I'll hand you to a specialist with the context already attached."
    );
  };

  return (
    <div className="push-enter" style={{ position: "absolute", inset: 0, zIndex: 320, background: "var(--bg)", display: "flex", flexDirection: "column" }} data-screen-label="Support">
      {window.StatusBar && <window.StatusBar />}

      {screen === "hub" && (
        <>
          <NavBar title="Help &amp; support"
            right={<button className="press" onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", display: "flex" }}><Icon name="close" size={20} /></button>} />
          <div className="scroll" style={{ padding: "10px 0 24px" }}>
            <div style={{ padding: "0 18px" }}>
              <SupportAskYoshi onClick={askYoshi} />
            </div>

            <div style={{ padding: "20px 18px 7px" }}><Eyebrow>Browse topics</Eyebrow></div>
            {SUPPORT_TOPICS.map((t, i) => (
              <button key={t.id} className="press" onClick={() => { setTopic(t); setScreen("topic"); }}
                style={{ width: "100%", display: "grid", gridTemplateColumns: "34px 1fr auto", gap: 12, alignItems: "center", padding: "12px 18px", background: "none", border: "none", borderTop: i === 0 ? "1px solid var(--rule)" : "none", borderBottom: "1px solid var(--rule)", textAlign: "left", cursor: "pointer" }}>
                <span style={{ width: 34, height: 34, display: "grid", placeItems: "center" }}><Icon name={t.icon} size={18} stroke={1.5} color="var(--ink)" /></span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: "var(--f-display)", fontSize: 14, fontWeight: 500 }}>{t.name}</div>
                  <div style={{ fontFamily: "var(--f-display)", fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>{t.sub}</div>
                </div>
                <Icon name="back" size={15} color="var(--ink-3)" style={{ transform: "scaleX(-1)" }} />
              </button>
            ))}

            <div style={{ padding: "20px 18px 7px" }}><Eyebrow>Talk to a person</Eyebrow></div>
            <div style={{ borderTop: "1px solid var(--rule)" }}>
              <SupportContactRow icon="chat" name="Message a specialist" sub="Avg wait under 2 min · 24/7" onClick={() => setScreen("chat")} tag="Fastest" />
              <SupportContactRow icon="mail" name="Email us" sub="support@yoshi.com · replies within a day" />
              <SupportContactRow icon="clock" name="Schedule a callback" sub="Pick a time, we'll ring you" last />
            </div>

            <div style={{ padding: "18px 18px 0" }}>
              <div style={{ fontFamily: "var(--f-display)", fontSize: 11, color: "var(--ink-3)", lineHeight: 1.6 }}>
                Lost or stolen card? Freeze it instantly in Accounts → Card, or message a specialist any hour. Yoshi never asks for your password or full card number.
              </div>
            </div>
          </div>
        </>
      )}

      {screen === "topic" && topic && (
        <SupportTopic topic={topic} onBack={() => setScreen("hub")} onClose={onClose} onChat={() => setScreen("chat")} onAsk={askYoshi} />
      )}

      {screen === "chat" && (
        <SupportChat onBack={onClose} onClose={onClose} />
      )}
    </div>
  );
};

/* ---- the agent-first lead card -------------------------------------------- */
const SupportAskYoshi = ({ onClick }) => {
  const logo = (window.__resources && window.__resources[useTheme() === "bone" ? "logoWhite" : "logoBlack"]) || "assets/logo-mark-white.png";
  return (
    <button className="press" onClick={onClick} style={{
      width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 13, padding: "15px 15px",
      background: "color-mix(in srgb, var(--accent) 12%, var(--bg-card))", border: "1px solid var(--accent)", borderRadius: 12, cursor: "pointer",
    }}>
      <span style={{ width: 40, height: 40, flex: "none", borderRadius: 999, background: "var(--accent)", display: "grid", placeItems: "center" }}>
        <img src={logo} alt="" style={{ height: 20, width: "auto" }} />
      </span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontFamily: "var(--f-display)", fontSize: 15, fontWeight: 600, letterSpacing: "-0.01em" }}>Ask Yoshi</div>
        <div style={{ fontFamily: "var(--f-display)", fontSize: 12, color: "var(--ink-2)", marginTop: 2, lineHeight: 1.4 }}>Yoshi can handle most questions. The agent can see your accounts and act on the right solution.</div>
      </div>
      <Icon name="back" size={16} color="var(--accent)" style={{ transform: "scaleX(-1)" }} />
    </button>
  );
};

const SupportContactRow = ({ icon, name, sub, onClick, tag, last }) => (
  <button className="press" onClick={onClick} disabled={!onClick}
    style={{ width: "100%", display: "grid", gridTemplateColumns: "34px 1fr auto", gap: 12, alignItems: "center", padding: "12px 18px", background: "none", border: "none", borderBottom: last ? "none" : "1px solid var(--rule)", textAlign: "left", cursor: onClick ? "pointer" : "default", opacity: onClick ? 1 : 0.92 }}>
    <span style={{ width: 34, height: 34, display: "grid", placeItems: "center" }}><Icon name={icon} size={18} stroke={1.5} color="var(--ink)" /></span>
    <div style={{ minWidth: 0 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
        <span style={{ fontFamily: "var(--f-display)", fontSize: 14, fontWeight: 500 }}>{name}</span>
        {tag && <span style={{ fontFamily: "var(--f-display)", fontSize: 8.5, fontWeight: 700, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--accent)", border: "1px solid color-mix(in srgb, var(--accent) 45%, transparent)", borderRadius: 999, padding: "1px 6px" }}>{tag}</span>}
      </div>
      <div style={{ fontFamily: "var(--f-display)", fontSize: 11.5, color: "var(--ink-3)", marginTop: 3 }}>{sub}</div>
    </div>
    {onClick && <Icon name="back" size={15} color="var(--ink-3)" style={{ transform: "scaleX(-1)" }} />}
  </button>
);

/* ---- topic detail · accordion FAQ ----------------------------------------- */
const SupportTopic = ({ topic, onBack, onClose, onChat, onAsk }) => {
  const [open, setOpen] = useState(0);
  return (
    <>
      <NavBar title={topic.name} onBack={onBack}
        right={<button className="press" onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", display: "flex" }}><Icon name="close" size={20} /></button>} />
      <div className="scroll" style={{ padding: "10px 18px 24px" }}>
        <Eyebrow>Common questions</Eyebrow>
        <div style={{ marginTop: 8, borderTop: "1px solid var(--rule)" }}>
          {topic.qs.map(([q, a], i) => {
            const on = open === i;
            return (
              <div key={i} style={{ borderBottom: "1px solid var(--rule)" }}>
                <button className="press" onClick={() => setOpen(on ? -1 : i)}
                  style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, padding: "13px 0", background: "none", border: "none", textAlign: "left", cursor: "pointer" }}>
                  <span style={{ flex: 1, fontFamily: "var(--f-display)", fontSize: 13.5, fontWeight: 500, lineHeight: 1.35 }}>{q}</span>
                  <Icon name={on ? "up" : "down"} size={16} color="var(--ink-3)" />
                </button>
                {on && (
                  <div style={{ padding: "0 0 14px" }}>
                    <Seam style={{ marginBottom: 11, opacity: 0.4 }} />
                    <div style={{ fontFamily: "var(--f-display)", fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.55 }}>{a}</div>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        <div style={{ marginTop: 20, padding: "14px 15px", border: "1px solid var(--rule)", background: "var(--bg-2)" }}>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 13.5, fontWeight: 600 }}>Still need help?</div>
          <div style={{ fontFamily: "var(--f-display)", fontSize: 11.5, color: "var(--ink-3)", marginTop: 3, lineHeight: 1.45 }}>Yoshi can act on most of these for you, or hand you to a specialist with the context attached.</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 12 }}>
            <Btn kind="ghost" onClick={onChat}>Message a specialist</Btn>
            <Btn onClick={onAsk}>Ask Yoshi</Btn>
          </div>
        </div>
      </div>
    </>
  );
};

/* ---- specialist live chat ------------------------------------------------- */
const SupportChat = ({ onBack, onClose }) => {
  const [msgs, setMsgs] = useState(SUPPORT_SEED);
  const [draft, setDraft] = useState("");
  const [typing, setTyping] = useState(false);
  const scrollRef = useRef(null);

  useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [msgs, typing]);

  const send = (text) => {
    const body = (text != null ? text : draft).trim();
    if (!body) return;
    setDraft("");
    setMsgs(m => [...m, { from: "user", t: body, time: "now" }]);
    setTyping(true);
    setTimeout(() => { setTyping(false); setMsgs(m => [...m, { from: "agent", t: supportReply(body), time: "now" }]); }, 1200);
  };

  const quick = ["A charge I don't recognize", "Where's my deposit?", "Freeze my card"];

  return (
    <>
      <NavBar title="Fin" sub="Yoshi support · powered by Fin" onBack={onBack}
        right={<button className="press" onClick={onClose} style={{ background: "none", border: "none", color: "var(--ink-3)", display: "flex" }}><Icon name="close" size={20} /></button>} />
      <div ref={scrollRef} className="scroll" style={{ padding: "14px 16px 8px", display: "flex", flexDirection: "column", gap: 10 }}>
        {msgs.map((m, i) => m.from === "sys" ? (
          <div key={i} style={{ textAlign: "center", padding: "2px 18px", margin: "0 auto", maxWidth: 300 }}>
            <span style={{ fontFamily: "var(--f-display)", fontSize: 10.5, color: "var(--ink-3)", lineHeight: 1.5 }}>{m.t}</span>
          </div>
        ) : (
          <div key={i} style={{ display: "flex", justifyContent: m.from === "user" ? "flex-end" : "flex-start" }}>
            <div style={{ maxWidth: "82%", padding: "9px 12px", borderRadius: 13, background: m.from === "user" ? "var(--accent)" : "var(--bg-2)", color: m.from === "user" ? "var(--accent-ink)" : "var(--ink)", border: m.from === "user" ? "none" : "1px solid var(--rule)" }}>
              <span style={{ fontFamily: "var(--f-display)", fontSize: 13.5, lineHeight: 1.45 }}>{m.t}</span>
            </div>
          </div>
        ))}
        {typing && (
          <div style={{ display: "flex", justifyContent: "flex-start" }}>
            <div style={{ padding: "11px 13px", borderRadius: 13, background: "var(--bg-2)", border: "1px solid var(--rule)", display: "flex", gap: 4 }}>
              {[0, 1, 2].map(d => <span key={d} className="yo-pulse" style={{ width: 5, height: 5, borderRadius: 999, background: "var(--ink-3)", animationDelay: `${d * 0.18}s` }} />)}
            </div>
          </div>
        )}
      </div>

      <div style={{ flex: "none" }}>
        {msgs.length <= 2 && (
          <div className="hcar" style={{ display: "flex", gap: 7, overflowX: "auto", padding: "4px 16px 10px" }}>
            {quick.map(q => (
              <button key={q} className="press" onClick={() => send(q)} style={{ flex: "none", padding: "7px 12px", borderRadius: 999, background: "color-mix(in srgb, var(--ink) 8%, var(--bg-2))", border: "none", fontFamily: "var(--f-display)", fontSize: 12, fontWeight: 500, color: "var(--ink-2)", whiteSpace: "nowrap", cursor: "pointer" }}>{q}</button>
            ))}
          </div>
        )}
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px 16px 20px", borderTop: "1px solid var(--rule)" }}>
          <input value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === "Enter") send(); }}
            placeholder="Message Avery…"
            style={{ flex: 1, padding: "11px 14px", background: "var(--bg-2)", border: "1px solid var(--rule-2)", outline: "none", color: "var(--ink)", fontFamily: "var(--f-display)", fontSize: 14 }} />
          <button className="press" onClick={() => send()} disabled={!draft.trim()} style={{ width: 42, height: 42, flex: "none", borderRadius: 10, background: "var(--accent)", border: "none", display: "grid", placeItems: "center", cursor: "pointer", opacity: draft.trim() ? 1 : 0.4 }}>
            <Icon name="send" size={18} color="var(--accent-ink)" />
          </button>
        </div>
      </div>
    </>
  );
};

window.SupportFlow = SupportFlow;
