// inbox.jsx — fan letters to Diaval. Curated monthly.
// Top: submission form (writes to diaval_inbox_messages).
// Below: letterbox of past issues (reads from diaval_inbox_archive).

function InboxPage({ tab, onTabChange }) {
  const S = window.shellStyles;
  const { isMobile } = (window.useViewport ? window.useViewport() : { isMobile: false });
  const [selectedMonth, setSelectedMonth] = React.useState(0);
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [submitError, setSubmitError] = React.useState(null);
  const [form, setForm] = React.useState({ name: "", location: "", age: "", email: "", body: "" });

  const [issues, setIssues] = React.useState([]);
  const [archiveLoading, setArchiveLoading] = React.useState(true);
  const [archiveError, setArchiveError] = React.useState(null);

  React.useEffect(() => {
    let cancelled = false;
    window.diavalSupabase
      .from("diaval_inbox_archive")
      .select("issue_month, issue_code, issue_note, received, answered, letter_from, letter_meta, letter_date, letter_body, letter_reply, featured, position")
      .eq("is_published", true)
      .order("issue_month", { ascending: false })
      .order("position", { ascending: true })
      .then(({ data, error }) => {
        if (cancelled) return;
        if (error) {
          setArchiveError(error.message);
        } else {
          // Group rows by issue (month/code/note) and collect their letters.
          const byKey = new Map();
          for (const row of data ?? []) {
            const key = `${row.issue_month}|${row.issue_code}`;
            let bucket = byKey.get(key);
            if (!bucket) {
              bucket = {
                month: row.issue_month,
                code: row.issue_code,
                received: row.received,
                answered: row.answered,
                note: row.issue_note,
                letters: [],
              };
              byKey.set(key, bucket);
            }
            if (row.letter_from || row.letter_body) {
              bucket.letters.push({
                from: row.letter_from,
                meta: row.letter_meta,
                date: row.letter_date,
                body: row.letter_body,
                reply: row.letter_reply,
                featured: !!row.featured,
              });
            }
          }
          setIssues(Array.from(byKey.values()));
        }
        setArchiveLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  const issue = issues[selectedMonth];

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    if (!form.body.trim()) { setSubmitError("Please write something."); return; }
    const email = form.email.trim().toLowerCase();
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setSubmitError("A real email is required so Diaval can reply (publicly or privately).");
      return;
    }
    // Consent popup — moved out of inline UI to keep the form uncluttered
    const ok = window.confirm("By sending, you agree your letter may be published anonymously in a future issue.\n\nSend it to the raven?");
    if (!ok) return;
    setSubmitting(true);
    setSubmitError(null);
    const payload = {
      name: form.name.trim() || null,
      location: form.location.trim() || null,
      age: form.age.trim() || null,
      email,
      body: form.body.trim(),
    };
    const { error } = await window.diavalSupabase
      .from("diaval_inbox_messages")
      .insert(payload);
    setSubmitting(false);
    if (error) {
      setSubmitError(error.message);
    } else {
      setSubmitted(true);
    }
  };

  return (
    <Shell tab={tab} onTabChange={onTabChange} page="006" broadcast="INBOX · LETTERS TO THE RAVEN">
      <div style={{
        position: isMobile ? "relative" : "absolute",
        inset: isMobile ? "auto" : 0,
        overflow: isMobile ? "visible" : "auto",
      }}>
        {/* page header */}
        <div style={{ padding: isMobile ? "20px 16px 16px" : "32px 56px 20px", borderBottom: `1px solid ${S.concreteHi}` }}>
          <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.3em", marginBottom: 8 }}>
            // VI. INBOX · WRITE TO THE RAVEN
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 32 }}>
            <h2 style={{
              margin: 0, fontFamily: S.display, fontSize: isMobile ? 28 : 56, lineHeight: 0.92,
              letterSpacing: "-0.02em", color: S.bone,
            }}>
              I READ ALL OF IT. <span style={{ color: S.bloodHot }}>I REPLY TO SOME.</span>
            </h2>
          </div>
        </div>

        {/* SECTION 1 — submission form */}
        <section style={{ padding: isMobile ? "24px 16px" : "40px 56px 32px" }}>
          <div>
            <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.4em", marginBottom: 8 }}>
              ⸺ SECTION 01 · WRITE ⸺
            </div>
            <h3 style={{
              margin: 0, fontFamily: S.display, fontSize: 32, color: S.bone,
              letterSpacing: "-0.01em", marginBottom: 24,
            }}>
              SEND A LETTER.
            </h3>

            {!submitted ? (
              <form onSubmit={handleSubmit}>
                <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr 120px", gap: 12, marginBottom: 12 }}>
                  <LetterInput label="NAME OR ALIAS" placeholder="anonymous · pen name · whatever" value={form.name} onChange={(v) => setForm({ ...form, name: v })} S={S} />
                  <LetterInput label="LOCATION" placeholder="city · country" value={form.location} onChange={(v) => setForm({ ...form, location: v })} S={S} />
                  <LetterInput label="AGE (OPT.)" placeholder="·" value={form.age} onChange={(v) => setForm({ ...form, age: v })} S={S} />
                </div>
                <div style={{ marginBottom: 12 }}>
                  <LetterInput
                    label="EMAIL · REQUIRED"
                    placeholder="for diaval to reply — publicly or privately"
                    value={form.email}
                    onChange={(v) => setForm({ ...form, email: v })}
                    S={S}
                  />
                </div>
                <div style={{ marginBottom: 12 }}>
                  <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", marginBottom: 6 }}>
                    YOUR LETTER
                  </div>
                  <textarea
                    value={form.body}
                    onChange={(e) => setForm({ ...form, body: e.target.value })}
                    placeholder="dear diaval, ...&#10;&#10;or: pitch a myth — &quot;you should make a song about cassandra because...&quot;"
                    rows={10}
                    style={{
                      width: "100%", boxSizing: "border-box", resize: "vertical",
                      padding: "14px 16px", background: S.raven,
                      border: `1px solid ${S.concreteHi}`, color: S.bone,
                      fontFamily: S.meta, fontSize: 13, lineHeight: 1.7, letterSpacing: "0.02em",
                      outline: "none",
                    }}
                    onFocus={(e) => (e.target.style.borderColor = S.bloodHot)}
                    onBlur={(e) => (e.target.style.borderColor = S.concreteHi)}
                  />
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: S.ashDim, letterSpacing: "0.25em", marginTop: 6 }}>
                    <span>{form.body.length} / 2000 CHARACTERS</span>
                    <span>· no length penalty. write what you need to write. ·</span>
                  </div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 16, marginTop: 18 }}>
                  <button type="submit" disabled={submitting} style={{
                    padding: "14px 32px", background: S.bloodHot, color: S.bone,
                    border: "none", fontFamily: S.display, fontSize: 13, letterSpacing: "0.25em",
                    cursor: submitting ? "wait" : "pointer", display: "flex", alignItems: "center", gap: 10,
                    opacity: submitting ? 0.6 : 1,
                  }}>
                    {submitting ? "TRANSMITTING…" : "SEND TO THE RAVEN"} <Glyph name="arrow" size={12} color={S.bone} />
                  </button>
                </div>
                {submitError && (
                  <div style={{
                    marginTop: 14, padding: "10px 14px",
                    border: `1px solid ${S.bloodHot}`, borderLeft: `3px solid ${S.bloodHot}`,
                    fontSize: 13, color: S.bone, fontFamily: S.meta, letterSpacing: "0.02em", lineHeight: 1.6,
                  }}>
                    <span style={{ color: S.bloodHot, letterSpacing: "0.3em", fontSize: 12 }}>◢ SIGNAL LOST · </span>
                    {submitError}
                  </div>
                )}
              </form>
            ) : (
              <div style={{
                border: `1px solid ${S.concreteHi}`, borderLeft: `3px solid ${S.bloodHot}`,
                padding: "32px 28px", background: S.concrete,
              }}>
                <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.4em", marginBottom: 14 }}>
                  ◢ DELIVERED · 2026.04.21 · 02:14 GMT
                </div>
                <div style={{ fontFamily: S.display, fontSize: 28, color: S.bone, letterSpacing: "-0.01em", lineHeight: 1.2, marginBottom: 16 }}>
                  THE RAVEN HAS YOUR LETTER.
                </div>
                <div style={{ fontFamily: S.meta, fontSize: 13, color: S.ash, lineHeight: 1.7, letterSpacing: "0.01em", marginBottom: 18 }}>
                  he reads everything. he answers some. if yours is picked, you'll see it appear in the next issue (MAY 2026, full moon, no promises) — published anonymously unless you said otherwise.<br /><br />
                  if not picked: it still went somewhere. that somewhere was him. that is not nothing.
                </div>
                <button onClick={() => { setSubmitted(false); setSubmitError(null); setForm({ name: "", location: "", age: "", body: "" }); }} style={{
                  padding: "10px 18px", background: "transparent", color: S.ash,
                  border: `1px solid ${S.concreteHi}`, fontFamily: S.display, fontSize: 13,
                  letterSpacing: "0.2em", cursor: "pointer",
                }}>
                  WRITE ANOTHER ◢
                </button>
              </div>
            )}
          </div>

        </section>

        {/* SECTION 2 — letterbox archive */}
        <section style={{
          padding: isMobile ? "24px 16px 32px" : "40px 56px 56px",
          borderTop: `1px solid ${S.concreteHi}`,
          background: `linear-gradient(180deg, ${S.raven} 0%, #050505 100%)`,
        }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 28, gap: 24 }}>
            <div>
              <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.4em", marginBottom: 8 }}>
                ⸺ SECTION 02 · LETTERBOX ⸺
              </div>
              <h3 style={{
                margin: 0, fontFamily: S.display, fontSize: 32, color: S.bone,
                letterSpacing: "-0.01em",
              }}>
                THE ONES <span style={{ color: S.bloodHot }}>HE ANSWERED.</span>
              </h3>
            </div>

            {/* issue switcher */}
            <div style={{ display: "flex", border: `1px solid ${S.concreteHi}`, fontSize: 12, letterSpacing: "0.25em" }}>
              {issues.map((iss, i) => (
                <button key={iss.month} onClick={() => setSelectedMonth(i)} style={{
                  padding: "12px 18px", fontFamily: S.meta,
                  background: selectedMonth === i ? S.concrete : "transparent",
                  color: selectedMonth === i ? S.bone : S.ash,
                  border: "none",
                  borderRight: i < issues.length - 1 ? `1px solid ${S.concreteHi}` : "none",
                  cursor: "pointer", textAlign: "left",
                }}>
                  <div style={{ fontFamily: S.display, fontSize: 13, letterSpacing: "0.04em", marginBottom: 2, color: selectedMonth === i ? S.bone : S.ash }}>
                    {iss.month}
                  </div>
                  <div style={{ fontSize: 12, color: selectedMonth === i ? S.bloodHot : S.ashDim, letterSpacing: "0.3em" }}>
                    {iss.code} · {iss.answered} ANSWERED
                  </div>
                </button>
              ))}
            </div>
          </div>

          {archiveLoading ? (
            <div style={{ padding: "60px 24px", textAlign: "center", fontSize: 13, color: S.ashDim, letterSpacing: "0.3em" }}>
              ⸺ TUNING SIGNAL ⸺
            </div>
          ) : archiveError ? (
            <div style={{ padding: "40px 24px", border: `1px solid ${S.bloodHot}`, borderLeft: `3px solid ${S.bloodHot}` }}>
              <div style={{ fontSize: 13, color: S.bloodHot, letterSpacing: "0.3em", marginBottom: 8 }}>◢ ARCHIVE FEED CORRUPTED</div>
              <div style={{ fontSize: 13, color: S.ash, fontStyle: "italic" }}>{archiveError}</div>
            </div>
          ) : !issue ? (
            <div style={{ padding: "60px 24px", textAlign: "center", fontSize: 13, color: S.ashDim, letterSpacing: "0.3em", border: `1px dashed ${S.concreteHi}` }}>
              ⸺ NO ISSUES YET ⸺
            </div>
          ) : (
            <>
              {/* issue header */}
              <div style={{
                border: `1px solid ${S.concreteHi}`,
                padding: isMobile ? "16px 16px" : "20px 24px",
                display: "grid",
                gridTemplateColumns: isMobile ? "1fr" : "1fr auto auto auto",
                gap: isMobile ? 16 : 32,
                alignItems: isMobile ? "flex-start" : "center",
                background: S.concrete, marginBottom: 24,
              }}>
                <div>
                  <div style={{ fontFamily: S.display, fontSize: 22, color: S.bone, letterSpacing: "-0.01em" }}>
                    {issue.month} · {issue.code}
                  </div>
                  <div style={{ fontSize: 13, color: S.ash, fontStyle: "italic", marginTop: 4, letterSpacing: "0.02em" }}>
                    {issue.note}
                  </div>
                </div>
                <div style={{ display: "flex", gap: isMobile ? 24 : 32, justifyContent: isMobile ? "space-around" : "flex-end", gridColumn: isMobile ? "1 / -1" : "auto" }}>
                  {[["RECEIVED", issue.received], ["ANSWERED", issue.answered], ["RATIO", issue.received ? `${((issue.answered/issue.received)*100).toFixed(1)}%` : "—"]].map(([k, v]) => (
                    <div key={k} style={{ textAlign: "center" }}>
                      <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", marginBottom: 4 }}>{k}</div>
                      <div style={{ fontFamily: S.display, fontSize: 22, color: S.bloodHot, letterSpacing: "-0.01em" }}>{v ?? "—"}</div>
                    </div>
                  ))}
                </div>
              </div>

              {/* letters */}
              {issue.letters.length === 0 ? (
                <div style={{
                  padding: "60px 24px", textAlign: "center",
                  border: `1px dashed ${S.concreteHi}`,
                  fontSize: 12, color: S.ashDim, letterSpacing: "0.3em",
                }}>
                  ARCHIVE BEING DIGITISED · CHECK BACK LATER
                </div>
              ) : (
                issue.letters.map((letter, i) => <Letter key={i} letter={letter} index={i + 1} total={issue.letters.length} S={S} />)
              )}
            </>
          )}

        </section>
      </div>
    </Shell>
  );
}

function LetterInput({ label, placeholder, value, onChange, S }) {
  return (
    <div>
      <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", marginBottom: 6 }}>{label}</div>
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: "100%", boxSizing: "border-box",
          padding: "10px 14px", background: S.raven,
          border: `1px solid ${S.concreteHi}`, color: S.bone,
          fontFamily: S.meta, fontSize: 12, letterSpacing: "0.02em", outline: "none",
        }}
        onFocus={(e) => (e.target.style.borderColor = S.bloodHot)}
        onBlur={(e) => (e.target.style.borderColor = S.concreteHi)}
      />
    </div>
  );
}

function Letter({ letter, index, total, S }) {
  const { isMobile } = (window.useViewport ? window.useViewport() : { isMobile: false });
  return (
    <div style={{
      border: `1px solid ${S.concreteHi}`, marginBottom: 24,
      borderLeft: letter.featured ? `3px solid ${S.bloodHot}` : `1px solid ${S.concreteHi}`,
      background: "#000",
    }}>
      {/* envelope header */}
      <div style={{
        padding: "14px 20px", borderBottom: `1px solid ${S.concreteHi}`,
        background: S.raven,
        display: "flex", justifyContent: "space-between", alignItems: "center",
        fontSize: 12, letterSpacing: "0.25em", fontFamily: S.meta,
      }}>
        <span style={{ color: S.bloodHot }}>
          ◢ LETTER {String(index).padStart(2, "0")} / {String(total).padStart(2, "0")}
          {letter.featured && <span style={{ marginLeft: 14, color: S.bone }}>· FEATURED</span>}
        </span>
        <span style={{ color: S.ashDim }}>{letter.date.toUpperCase()}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 0 }}>
        {/* incoming letter */}
        <div style={{
          padding: isMobile ? "20px 18px" : "28px 30px",
          borderRight: isMobile ? "none" : `1px solid ${S.concreteHi}`,
          borderBottom: isMobile ? `1px solid ${S.concreteHi}` : "none",
        }}>
          <div style={{ fontSize: 12, color: S.ashDim, letterSpacing: "0.3em", marginBottom: 18 }}>
            ↓ INCOMING
          </div>
          <div style={{
            fontFamily: "'Courier New', 'JetBrains Mono', monospace",
            fontSize: 13, color: S.bone, lineHeight: 1.85, letterSpacing: "0.01em",
            whiteSpace: "pre-wrap",
          }}>
            {letter.body}
          </div>
          <div style={{
            marginTop: 24, paddingTop: 14, borderTop: `1px dashed ${S.concreteHi}`,
            fontSize: 13, color: S.ash, fontFamily: S.meta, letterSpacing: "0.04em", lineHeight: 1.5,
          }}>
            <span style={{ color: S.bloodHot }}>— {letter.from}</span><br />
            <span style={{ color: S.ashDim, fontSize: 12, fontStyle: "italic" }}>{letter.meta}</span>
          </div>
        </div>

        {/* reply */}
        <div style={{ padding: isMobile ? "20px 18px" : "28px 30px", background: "rgba(190,33,30,0.04)" }}>
          <div style={{ fontSize: 12, color: S.bloodHot, letterSpacing: "0.3em", marginBottom: 18 }}>
            ↑ REPLY · D//V
          </div>
          <div style={{
            fontFamily: S.meta,
            fontSize: 13.5, color: S.bone, lineHeight: 1.85, letterSpacing: "0.005em",
            whiteSpace: "pre-wrap",
          }}>
            {letter.reply}
          </div>
        </div>
      </div>
    </div>
  );
}

window.InboxPage = InboxPage;
