/* FindMyFrag — /authenticate.
   Batch-code decoder. Reader inputs the short alphanumeric code from the
   box-bottom or bottle-base; we decode production year, quarter, line, and
   cross-reference the §4 authenticity-complaint log. Not proof — a first
   pass that flags obvious fakes and surfaces known-incident batches. */

/* global React, FMF */

function Authenticate({ initialCode }) {
  const [code, setCode] = React.useState(initialCode || "");
  const [submitted, setSubmitted] = React.useState(!!initialCode);
  const inputRef = React.useRef(null);

  React.useEffect(() => { if (!initialCode) inputRef.current?.focus(); }, [initialCode]);

  const decoded = React.useMemo(() => submitted ? FMF.decodeBatch(code) : null, [code, submitted]);

  function submit(e) {
    e?.preventDefault();
    setSubmitted(true);
    const enc = encodeURIComponent(code.trim());
    if (code.trim()) location.hash = `/authenticate?code=${enc}`;
  }

  return (
    <main>
      {/* Masthead */}
      <section className="container" style={{ paddingTop: 28, paddingBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
          <div className="kicker">Authentication · batch-code decoder</div>
          <div className="mono body-xs" style={{ color: "var(--ink-mute)" }}>
            Refusal §4 · batch-code complaint log · <a href="#/refusals#batch-code-complaint" style={{ color: "var(--ink-mute)", borderBottom: "1px solid var(--rule)", paddingBottom: 1 }}>policy</a>
          </div>
        </div>
      </section>
      <hr className="hairline-k" />

      {/* Cover */}
      <section className="container" style={{ padding: "56px 32px 24px" }}>
        <h1 className="display-xl" style={{ margin: 0, maxWidth: "16ch" }}>
          Decode a <span className="fraun-itl">batch code</span>.
        </h1>
        <p className="fraun body-l" style={{ color: "var(--ink-soft)", marginTop: 20, maxWidth: "56ch" }}>
          Most fragrance bottles carry a short alphanumeric code on the
          box-bottom and bottle-base. It encodes when and where the bottle
          was produced. This page decodes formats we know; cross-references
          the §4 complaint log; and tells you plainly when it can't.
        </p>
      </section>

      {/* Input */}
      <section className="container" style={{ padding: "24px 32px 12px" }}>
        <form onSubmit={submit} style={{ maxWidth: 680 }}>
          <label className="mono body-xs" htmlFor="batch-input" style={{ color: "var(--ink-mute)", letterSpacing: "0.1em", textTransform: "uppercase" }}>
            Code · as printed on the bottle
          </label>
          <div style={{ display: "flex", alignItems: "center", gap: 14, borderTop: "1px solid var(--ink)", borderBottom: "2px solid var(--ink)", padding: "18px 8px 14px", marginTop: 10 }}>
            <input
              ref={inputRef}
              id="batch-input"
              value={code}
              onChange={(e) => { setCode(e.target.value); setSubmitted(false); }}
              placeholder="e.g. A3L5 · 2239 · EF06"
              className="mono"
              style={{
                flex: 1, border: 0, background: "transparent", outline: "none",
                fontSize: 26, letterSpacing: "0.04em", color: "var(--ink)",
                padding: "2px 0",
                textTransform: "uppercase",
              }}
              aria-label="Batch code"
              autoComplete="off"
            />
            <button type="submit" className="shop-btn shop-btn--primary" style={{ padding: "10px 18px" }}>
              Decode
            </button>
          </div>
          <div className="mono body-xs" style={{ color: "var(--ink-mute)", marginTop: 10, letterSpacing: "0.04em" }}>
            Formats we know in Issue 001 · Creed <span style={{ color: "var(--ink)" }}>LDLN</span> · Tom Ford <span style={{ color: "var(--ink)" }}>NYYM</span>. Other brands will decode to "format not recognized" until we add them.
          </div>
        </form>
      </section>

      {/* Result */}
      {decoded && (
        <section className="container" style={{ padding: "28px 32px 56px" }}>
          {decoded.unknown ? <UnknownResult d={decoded} /> : <DecodedResult code={code.trim().toUpperCase()} d={decoded} />}
        </section>
      )}

      <hr className="hairline" />

      {/* Method */}
      <section className="container" style={{ padding: "48px 32px 64px" }}>
        <div className="stack-mobile" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48 }}>
          <div>
            <div className="kicker" style={{ marginBottom: 14 }}>What this is</div>
            <p className="body-l" style={{ color: "var(--ink-soft)", margin: 0, maxWidth: "52ch" }}>
              A first-pass check against known brand schemas. Most counterfeit bottles carry codes that don't conform to the real format — this catches the obvious ones. For ambiguous codes we say so. We do not certify authenticity.
            </p>
          </div>
          <div>
            <div className="kicker" style={{ marginBottom: 14 }}>What this isn't</div>
            <p className="body-l" style={{ color: "var(--ink-soft)", margin: 0, maxWidth: "52ch" }}>
              Not a certificate. Not a guarantee. A formatted code on a bottle tells you the code is plausible; the juice inside is a separate question. For real authentication: batch-code match + cap weight + spray pattern + scent profile against a reference bottle.
            </p>
          </div>
        </div>
      </section>
    </main>
  );
}

function DecodedResult({ code, d }) {
  const clean = !d.complaints || d.complaints.length === 0;
  return (
    <div style={{ border: "1px solid var(--ink)", padding: "28px 32px" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 20, flexWrap: "wrap", gap: 10 }}>
        <div className="kicker">Decoded</div>
        <div className="mono body-xs" style={{ color: "var(--ink-mute)" }}>
          {d.confidence}
        </div>
      </div>

      <div className="stack-mobile" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 48, alignItems: "start" }}>
        <div>
          <div className="mono body-xs" style={{ color: "var(--ink-mute)", letterSpacing: "0.1em", textTransform: "uppercase", marginBottom: 10 }}>
            Code
          </div>
          <div className="mono" style={{ fontSize: 56, letterSpacing: "0.04em", color: "var(--ink)", lineHeight: 1 }}>{code}</div>
          <div className="mono body-xs" style={{ color: "var(--ink-mute)", marginTop: 10 }}>
            format <strong style={{ color: "var(--ink)" }}>{d.format}</strong>
          </div>
        </div>
        <div style={{ fontFamily: "var(--font-mono)", fontSize: 13, lineHeight: 2 }}>
          <DecodeRow k="brand"         v={d.brand} />
          {d.plausibleYears && <DecodeRow k="year" v={d.plausibleYears.join(" or ")} />}
          {d.quarter   && <DecodeRow k="quarter"  v={`Q${d.quarter}`} />}
          {d.month     && <DecodeRow k="month"    v={d.month} />}
          {d.line      && <DecodeRow k="line"     v={d.line} />}
          {typeof d.batch === "number" && <DecodeRow k="batch" v={d.batch} />}
          {d.facility  && <DecodeRow k="facility" v={d.facility} />}
          <DecodeRow k="§4 log" v={clean
            ? <span style={{ color: "var(--sig-buy)" }}>clean · no complaints in trailing 12 months</span>
            : <span style={{ color: "var(--oxblood-ink)" }}>flagged · {d.complaints.length} complaint(s) — see log</span>
          } />
        </div>
      </div>

      <div className="body-s" style={{ color: "var(--ink-mute)", marginTop: 24, borderTop: "1px solid var(--rule)", paddingTop: 16, maxWidth: "60ch" }}>
        This is a <strong style={{ color: "var(--ink)" }}>plausibility check</strong>, not a certificate. The code conforms to the known {d.brand} schema. Final authentication still requires a physical inspection — cap weight, spray pattern, and scent profile against a reference bottle.
      </div>
    </div>
  );
}

function UnknownResult({ d }) {
  return (
    <div style={{ border: "2px solid var(--oxblood)", padding: "28px 32px" }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 20, flexWrap: "wrap", gap: 10 }}>
        <div className="kicker" style={{ color: "var(--oxblood-ink)" }}>Format not recognized</div>
        <div className="mono body-xs" style={{ color: "var(--ink-mute)" }}>
          §4 · authenticity policy
        </div>
      </div>

      <div className="mono" style={{ fontSize: 40, letterSpacing: "0.04em", color: "var(--ink)", lineHeight: 1, marginBottom: 18 }}>
        {d.raw}
      </div>

      <p className="body-l" style={{ color: "var(--ink-soft)", margin: 0, maxWidth: "56ch" }}>
        {d.note}
      </p>

      <div className="mono body-s" style={{ color: "var(--ink-mute)", marginTop: 24, lineHeight: 1.9, borderTop: "1px solid var(--rule)", paddingTop: 16 }}>
        What we would need to decode this:
        <ul style={{ margin: "6px 0 0", paddingLeft: 18, color: "var(--ink-soft)" }}>
          <li>Brand-of-record (Dior, Chanel, Guerlain, etc.)</li>
          <li>Full code length and any separators visible on the bottle</li>
          <li>Photo of the box-bottom — the code may pair with a second stamp</li>
        </ul>
      </div>
    </div>
  );
}

function DecodeRow({ k, v }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", borderTop: "1px solid var(--rule)", padding: "7px 0" }}>
      <span style={{ color: "var(--ink-mute)", letterSpacing: "0.06em", textTransform: "uppercase", fontSize: 11 }}>{k}</span>
      <span style={{ color: "var(--ink)", textAlign: "right" }}>{v}</span>
    </div>
  );
}

Object.assign(window, { Authenticate });
