/* global React, window */
/* SHEET CREATOR — aba "Ficha" do grimório. Preview + exportação. */

(function () {
  "use strict";
  const { useState, useEffect, useCallback } = React;

  function lsGet(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }
  function lsSet(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} }

  function FcCorners() {
    return (
      <>
        <span className="frame-corner tl"/>
        <span className="frame-corner tr"/>
        <span className="frame-corner bl"/>
        <span className="frame-corner br"/>
      </>
    );
  }

  function useCharName() {
    const [name, setName] = useState(() => lsGet("arton_char_name") || "");
    useEffect(() => {
      const onChange = () => setName(lsGet("arton_char_name") || "");
      window.addEventListener("arton:char-changed", onChange);
      window.addEventListener("storage", onChange);
      return () => {
        window.removeEventListener("arton:char-changed", onChange);
        window.removeEventListener("storage", onChange);
      };
    }, []);
    const update = useCallback((v) => {
      setName(v);
      lsSet("arton_char_name", v);
      try { window.dispatchEvent(new CustomEvent("arton:char-changed")); } catch {}
    }, []);
    return [name, update];
  }

  function buildSummary() {
    const cls    = lsGet("arton_char_class") || { classes: [] };
    const race   = lsGet("arton_char_race");
    const origin = lsGet("arton_char_origin");
    const deity  = lsGet("arton_char_deity");
    const attrs  = lsGet("arton_char_attrs");
    const skills = lsGet("arton_skills") || {};
    const classes = (cls.classes || []).filter(c => c.className);
    const totalLevel = classes.reduce((a, c) => a + (c.level || 0), 0);
    return {
      classes,
      race, origin, deity, attrs,
      totalLevel,
      classCount: classes.length,
      skillsChosen: (skills.choices || []).length + (skills.int_bonus_choices || []).length,
      hasAttrs: !!(attrs && (attrs.base_buy || attrs.base_roll)),
    };
  }

  function useCharSummary() {
    const [s, setS] = useState(() => buildSummary());
    useEffect(() => {
      const onChange = () => setS(buildSummary());
      window.addEventListener("arton:char-changed", onChange);
      document.addEventListener("arton:char-changed", onChange);
      window.addEventListener("storage", onChange);
      return () => {
        window.removeEventListener("arton:char-changed", onChange);
        document.removeEventListener("arton:char-changed", onChange);
        window.removeEventListener("storage", onChange);
      };
    }, []);
    return s;
  }

  function SheetCreator() {
    const [name, setName]   = useCharName();
    const summary           = useCharSummary();
    const [status, setStatus] = useState(null);
    const [busy, setBusy]   = useState(false);
    const [importOpen, setImportOpen] = useState(false);

    const missing = [];
    if (!summary.classCount)  missing.push("Classe");
    if (!summary.hasAttrs)    missing.push("Atributos");
    if (!summary.race)        missing.push("Raça");
    if (!summary.origin)      missing.push("Origem");

    const canExport = !!name.trim();

    const onExport = async () => {
      setBusy(true); setStatus(null);
      try {
        const res = await window.SHEET_EXPORT.downloadPdf(name);
        setStatus({ type: "ok", msg: `Baixado: ${res.filename}` });
      } catch (e) {
        setStatus({ type: "err", msg: e.message || String(e) });
      } finally {
        setBusy(false);
      }
    };

    const onCopyCode = async () => {
      try {
        const payload = window.SHEET_EXPORT.buildPayload(name);
        const code = window.SHEET_EXPORT.encodeCode(payload);
        await navigator.clipboard.writeText(code);
        setStatus({ type: "ok", msg: "Código copiado para a área de transferência" });
      } catch (e) {
        setStatus({ type: "err", msg: e.message || String(e) });
      }
    };

    return (
      <div className="cc-root fc-root">
        <div className="spread-frame">
          <div className="page left">
            <FcCorners/>
            <div className="page-content fc-preview">
              <header className="page-header">
                <span className="page-eyebrow">Ficha · Pré-visualização</span>
                <span className="page-folio">{summary.totalLevel ? `nível ${summary.totalLevel}` : "—"}</span>
              </header>
              <h1 className="page-title">Visão Geral</h1>
              <p className="page-subtitle">Confira o que entrará no PDF antes de exportar.</p>

              <section className="fc-summary">
                <div className="fc-sum-row">
                  <span className="fc-sum-label">Classes</span>
                  <span className="fc-sum-val">
                    {summary.classes.length
                      ? summary.classes.map(c => `${c.className} ${c.level}`).join(" · ")
                      : <em className="fc-empty">não definida</em>}
                  </span>
                </div>
                <div className="fc-sum-row">
                  <span className="fc-sum-label">Raça</span>
                  <span className="fc-sum-val">
                    {summary.race ? `${summary.race.name}${summary.race.variant ? ` (${summary.race.variant})` : ""}` : <em className="fc-empty">não definida</em>}
                  </span>
                </div>
                <div className="fc-sum-row">
                  <span className="fc-sum-label">Origem</span>
                  <span className="fc-sum-val">{(summary.origin && summary.origin.name) || <em className="fc-empty">não definida</em>}</span>
                </div>
                <div className="fc-sum-row">
                  <span className="fc-sum-label">Divindade</span>
                  <span className="fc-sum-val">{(summary.deity && summary.deity.name) || <em className="fc-empty">sem devoção</em>}</span>
                </div>
                <div className="fc-sum-row">
                  <span className="fc-sum-label">Atributos</span>
                  <span className="fc-sum-val">{summary.hasAttrs ? "definidos" : <em className="fc-empty">não definidos</em>}</span>
                </div>
                <div className="fc-sum-row">
                  <span className="fc-sum-label">Perícias escolhidas</span>
                  <span className="fc-sum-val">{summary.skillsChosen}</span>
                </div>
              </section>

              {missing.length > 0 && (
                <div className="fc-warn">
                  <strong>Atenção:</strong> faltam preencher — {missing.join(", ")}. O PDF é gerado mesmo assim, mas com seções vazias.
                </div>
              )}
            </div>
          </div>

          <div className="page right">
            <FcCorners/>
            <div className="page-content fc-actions">
              <header className="page-header">
                <span className="page-eyebrow">Ficha · Exportar</span>
                <span className="page-folio">PDF · 3 págs</span>
              </header>
              <h1 className="page-title">Exportar Ficha</h1>

              <label className="fc-field">
                <span className="fc-field-lbl">Nome do personagem</span>
                <input
                  type="text"
                  className="fc-input"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Ex: Aragorn, filho de Arathorn"
                />
              </label>

              <button
                className="fc-export-btn"
                disabled={!canExport || busy}
                onClick={onExport}
                title={!canExport ? "Defina um nome do personagem" : "Gerar PDF"}
              >
                {busy ? "Gerando..." : "Exportar PDF"}
              </button>

              <div className="fc-code-section">
                <h3 className="fc-h3">Código da ficha</h3>
                <p className="fc-help">
                  O PDF inclui um código no rodapé que permite reimportar este personagem
                  para edição no Escriba. Você pode copiar agora ou após exportar.
                </p>
                <div className="fc-code-actions">
                  <button className="fc-code-btn" onClick={onCopyCode} disabled={!canExport}>
                    Copiar código
                  </button>
                  <button
                    className="fc-code-btn fc-code-btn--primary"
                    onClick={() => setImportOpen(true)}
                    title="Cole um código previamente gerado para carregar o personagem"
                  >
                    Importar ficha…
                  </button>
                </div>
              </div>

              {status && (
                <div className={`fc-status fc-status--${status.type}`} role="status">
                  {status.msg}
                </div>
              )}
            </div>
          </div>
        </div>
        {window.ImportSheetModal && (
          <window.ImportSheetModal open={importOpen} onClose={() => setImportOpen(false)} />
        )}
      </div>
    );
  }

  window.SheetCreator = SheetCreator;
})();
