// ============================================================
//  Mobile — Report (with auto-save), Posts, Home/Site, Terms
//  Loads after profile-v2.jsx
// ============================================================

const CATS_V2 = ["Roads", "Water", "Power", "Safety", "Civic Infrastructure", "Cultural Wealth", "Other"];

// ============================ REPORT SCREEN ============================
function ReportScreen({ editing, onSaveDraft, onSubmit, onDelete, onDirty }) {
  const isEdit = editing && editing.id != null;
  const [lang, setLang] = React.useState("en");
  const [title, setTitle] = React.useState(editing?.title || "");
  const [desc, setDesc] = React.useState(editing?.body || "");
  const [cat, setCat] = React.useState(editing?.cat || "Roads");
  const [loc, setLoc] = React.useState(editing?.location || "Kanchipuram, TN");
  const [dirty, setDirtyLocal] = React.useState(false);
  const [autoSaved, setAutoSaved] = React.useState(null);
  const [saving, setSaving] = React.useState(false);

  const initRef = React.useRef(JSON.stringify({
    title: editing?.title || "", desc: editing?.body || "",
    cat: editing?.cat || "Roads", loc: editing?.location || "Kanchipuram, TN",
  }));
  const autoSaveTimer = React.useRef(null);

  React.useEffect(() => {
    const isDirty = JSON.stringify({ title, desc, cat, loc }) !== initRef.current;
    setDirtyLocal(isDirty);
    onDirty && onDirty(isDirty);

    // auto-save after 3 seconds of inactivity
    if (isDirty && title.trim().length > 3) {
      clearTimeout(autoSaveTimer.current);
      autoSaveTimer.current = setTimeout(() => {
        setSaving(true);
        setTimeout(() => {
          setSaving(false);
          const now = new Date();
          setAutoSaved(now.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }));
        }, 600);
      }, 3000);
    }
    return () => clearTimeout(autoSaveTimer.current);
  }, [title, desc, cat, loc]);

  const payload = () => ({ title: title.trim(), body: desc.trim(), cat, location: loc.trim() });
  const canSubmit = title.trim().length > 3 && desc.trim().length > 8;

  const L = {
    en: { head: "Headline", desc: "Description", cat: "Category", loc: "Location",
      hph: "What happened?", dph: "Describe the situation on the ground…" },
    ta: { head: "தலைப்பு", desc: "விவரம்", cat: "வகை", loc: "இடம்",
      hph: "என்ன நடந்தது?", dph: "நிலைமையை விளக்குங்கள்…" },
  }[lang];

  return (
    <div style={{ padding: "16px 16px 30px", background: "var(--bg-app)", minHeight: "100%" }}>
      {/* header + auto-save */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between",
        marginBottom: 14 }}>
        <div>
          <h1 style={{ margin: 0, fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 21,
            color: "var(--text)", letterSpacing: "-0.01em" }}>
            {isEdit ? "Edit article" : "Report a Story"}</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 6 }}>
            {isEdit && <Badge status={editing.status} size="sm" />}
            <AutoSaveIndicator dirty={dirty} saving={saving} lastSaved={autoSaved} />
          </div>
        </div>
        <div style={{ display: "flex", background: "var(--bg-card)", borderRadius: 9, padding: 3,
          border: "1px solid var(--border)" }}>
          {[["ta", "தமிழ்"], ["en", "EN"]].map(([k, l]) => (
            <button key={k} onClick={() => setLang(k)} style={{ padding: "5px 11px", borderRadius: 7,
              fontSize: 12.5, fontWeight: 600, fontFamily: "var(--ff-ui)", border: "none",
              cursor: "pointer", transition: "all .15s ease",
              color: lang === k ? "#fff" : "var(--subtext)",
              background: lang === k ? "var(--blue)" : "transparent" }}>{l}</button>
          ))}
        </div>
      </div>

      {/* requested-changes banner */}
      {isEdit && editing.status === "CHANGES REQ." && editing.note && (
        <div style={{ display: "flex", gap: 10, padding: "12px 14px", borderRadius: 11,
          marginBottom: 16,
          background: "color-mix(in srgb, var(--st-review) 11%, transparent)",
          border: "1px solid color-mix(in srgb, var(--st-review) 45%, transparent)" }}>
          <span style={{ color: "var(--st-review)", flexShrink: 0, marginTop: 1 }}>
            <Icons.edit size={16} /></span>
          <div>
            <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 12.5,
              color: "var(--st-review)", marginBottom: 3 }}>Editor requested changes</div>
            <div style={{ fontFamily: "var(--ff-ui)", fontSize: 13.5, lineHeight: 1.5,
              color: "var(--text-2)" }}>{editing.note}</div>
          </div>
        </div>
      )}

      <FormField label={L.head}><input value={title} onChange={(e) => setTitle(e.target.value)}
        style={nkInput} placeholder={L.hph} /></FormField>
      <FormField label={L.desc}><textarea value={desc} onChange={(e) => setDesc(e.target.value)}
        rows={5} style={{ ...nkInput, resize: "none", lineHeight: 1.5 }}
        placeholder={L.dph} /></FormField>

      <FormField label={L.cat}>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 7 }}>
          {CATS_V2.map((c) => (
            <Pill key={c} active={cat === c} onClick={() => setCat(c)} mono={false}>{c}</Pill>
          ))}
        </div>
      </FormField>

      <FormField label={L.loc}>
        <div style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 12, top: 13, color: "var(--red)" }}>
            <Icons.pin size={18} /></span>
          <input value={loc} onChange={(e) => setLoc(e.target.value)}
            style={{ ...nkInput, paddingLeft: 38 }} />
        </div>
      </FormField>

      {/* media upload */}
      <div style={{ border: "1.6px dashed var(--border-2)", borderRadius: 11,
        background: "var(--bg-sunken)", padding: "20px 16px", textAlign: "center",
        marginBottom: 18, color: "var(--text-2)" }}>
        <div style={{ display: "grid", placeItems: "center", marginBottom: 8 }}>
          <div style={{ width: 46, height: 46, borderRadius: 12, display: "grid",
            placeItems: "center", background: "var(--blue-tint)",
            color: "var(--blue)" }}><Icons.camera size={24} /></div>
        </div>
        <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 14.5,
          color: "var(--text)" }}>
          {editing?.hasMedia ? "1 photo attached" : "Add photo or video"}</div>
        <div style={{ fontFamily: "var(--ff-ui)", fontSize: 11.5, marginTop: 5,
          color: "var(--subtext)" }}>Min. 720p · Max. 50 MB</div>
      </div>

      {/* actions */}
      <div style={{ display: "flex", gap: 10 }}>
        <button onClick={() => onSaveDraft(payload())} style={{ flex: "0 0 auto",
          padding: "13px 16px", borderRadius: 11, background: "var(--bg-card)",
          color: "var(--text-2)", border: "1px solid var(--border-2)",
          fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 14.5,
          cursor: "pointer", display: "flex", alignItems: "center", gap: 7 }}>
          <Icons.save size={17} /> Save draft
        </button>
        <button onClick={() => canSubmit && onSubmit(payload())} disabled={!canSubmit}
          style={{ flex: 1, padding: "13px", borderRadius: 11,
            fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 15,
            color: "#fff", background: canSubmit ? "var(--blue)" : "var(--border-2)",
            border: "none", cursor: canSubmit ? "pointer" : "not-allowed",
            display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
            boxShadow: canSubmit ? "0 6px 16px rgba(0,68,187,0.28)" : "none",
            transition: "all .15s ease" }}>
          {isEdit && editing.status !== "DRAFT" ? "Resubmit" : "Submit report"} <Icons.send size={17} />
        </button>
      </div>

      {isEdit && (
        <button onClick={() => onDelete(editing)} style={{ width: "100%", marginTop: 14,
          padding: "11px", borderRadius: 11, background: "none", color: "var(--red)",
          border: "none", fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 14,
          cursor: "pointer", display: "flex", alignItems: "center",
          justifyContent: "center", gap: 7 }}>
          <Icons.trash size={16} /> Delete {editing.status === "DRAFT" ? "draft" : "article"}
        </button>
      )}
    </div>
  );
}

const FormField = ({ label, children }) => (
  <label style={{ display: "block", marginBottom: 16 }}>
    <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 14.5,
      color: "var(--text)", marginBottom: 7 }}>{label}</div>
    {children}
  </label>
);

// ============================ POSTS ============================
const POST_FILTERS_V2 = [
  { label: "All", match: () => true },
  { label: "Published", match: (s) => s.status === "APPROVED" },
  { label: "In review", match: (s) => s.status === "UNDER REVIEW" },
  { label: "Needs edit", match: (s) => s.status === "CHANGES REQ." },
  { label: "Held", match: (s) => s.status === "HELD" },
  { label: "Drafts", match: (s) => s.status === "DRAFT" },
];
const EDITABLE_V2 = ["DRAFT", "CHANGES REQ."];

function PostsScreen({ posts, onEdit, onNew }) {
  const [fi, setFi] = React.useState(0);
  const list = posts.filter(POST_FILTERS_V2[fi].match);
  return (
    <div style={{ background: "var(--bg-app)", minHeight: "100%", padding: "16px 16px 30px" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
        marginBottom: 14, gap: 10 }}>
        <div>
          <h1 style={{ margin: 0, fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 21,
            color: "var(--text)", letterSpacing: "-0.01em" }}>Your posts</h1>
          <span style={{ fontFamily: "var(--ff-ui)", fontSize: 12.5,
            color: "var(--subtext)" }}>{posts.length} total</span>
        </div>
        <button onClick={onNew} style={{ flexShrink: 0, display: "inline-flex",
          alignItems: "center", gap: 6, padding: "9px 14px", borderRadius: 10,
          background: "var(--blue)", color: "#fff", border: "none", cursor: "pointer",
          fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 13.5,
          boxShadow: "0 5px 14px rgba(0,68,187,0.28)" }}>
          <Icons.plus size={17} sw={2.3} /> New report
        </button>
      </div>

      <div style={{ display: "flex", gap: 7, marginBottom: 16, flexWrap: "wrap" }}>
        {POST_FILTERS_V2.map((f, i) => (
          <Pill key={f.label} active={fi === i} onClick={() => setFi(i)}
            mono={false}>{f.label}</Pill>
        ))}
      </div>

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {list.map((s) => {
          const editable = EDITABLE_V2.includes(s.status);
          return (
            <div key={s.id} onClick={() => editable && onEdit(s.id)}
              style={{ background: "var(--bg-card)", borderRadius: 12,
                border: "1px solid var(--border)", padding: 13,
                boxShadow: "var(--shadow-sm)",
                cursor: editable ? "pointer" : "default",
                transition: "border-color .15s ease" }}>
              <div style={{ display: "flex", justifyContent: "space-between",
                alignItems: "flex-start", gap: 10, marginBottom: 10 }}>
                <div style={{ fontFamily: "var(--ff-serif)", fontWeight: 700, fontSize: 16.5,
                  lineHeight: 1.25, color: "var(--text)" }}>{s.title}</div>
                <Badge status={s.status} size="sm" />
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 10,
                fontFamily: "var(--ff-ui)", fontSize: 12.5, color: "var(--subtext)" }}>
                <span>{s.date}</span>
                <span style={{ width: 3, height: 3, borderRadius: 9,
                  background: "var(--border-2)" }} />
                <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
                  <Icons.eye size={14} /> {s.views} views</span>
                {editable ? (
                  <span style={{ marginLeft: "auto", display: "inline-flex",
                    alignItems: "center", gap: 4, color: "var(--blue)", fontWeight: 600 }}>
                    <Icons.edit size={13} />
                    {s.status === "CHANGES REQ." ? "Fix & resubmit" : "Edit"}
                  </span>
                ) : (
                  <span style={{ marginLeft: "auto", fontFamily: "var(--ff-ui)",
                    fontSize: 11.5, color: "var(--text-2)" }}>{s.cat}</span>
                )}
              </div>
            </div>
          );
        })}
        {list.length === 0 && (
          <div style={{ textAlign: "center", padding: "50px 20px", color: "var(--subtext)" }}>
            <div style={{ width: 52, height: 52, borderRadius: 14, background: "var(--bg-sunken)",
              display: "grid", placeItems: "center", margin: "0 auto 14px",
              border: "1px solid var(--border)" }}>
              <Icons.news size={26} style={{ color: "var(--border-2)" }} />
            </div>
            <div style={{ fontFamily: "var(--ff-ui)", fontSize: 15, fontWeight: 600,
              color: "var(--text-2)", marginBottom: 4 }}>No posts here yet</div>
            <div style={{ fontFamily: "var(--ff-ui)", fontSize: 13,
              lineHeight: 1.4 }}>Posts matching this filter will appear here.</div>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================ HOME / SITE ============================
function HomeSiteScreen() {
  const URL = "https://www.nambikkai.com";
  const [nonce, setNonce] = React.useState(0);
  const [loaded, setLoaded] = React.useState(false);
  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column",
      background: "var(--bg-app)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 12px",
        borderBottom: "1px solid var(--border)", background: "var(--bg-card)" }}>
        <span style={{ color: "var(--subtext)" }}><Icons.globe size={16} /></span>
        <div style={{ flex: 1, fontFamily: "var(--ff-ui)", fontSize: 12.5,
          color: "var(--text-2)", background: "var(--bg-sunken)",
          border: "1px solid var(--border)", borderRadius: 8, padding: "7px 11px",
          overflow: "hidden", whiteSpace: "nowrap",
          display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ color: "var(--st-approve)" }}><Icons.lock size={12} /></span> nambikkai.com
        </div>
        <button onClick={() => { setLoaded(false); setNonce((n) => n + 1); }}
          style={{ color: "var(--subtext)", background: "none", border: "none",
            cursor: "pointer", padding: 4 }}>
          <Icons.refresh size={16} />
        </button>
      </div>
      <div style={{ flex: 1, position: "relative", background: "#fff" }}>
        <iframe key={nonce} src={URL} title="Nambikkai.com"
          onLoad={() => setLoaded(true)}
          style={{ width: "100%", height: "100%", border: "none", display: "block" }} />
        {!loaded && (
          <div style={{ position: "absolute", inset: 0, display: "flex",
            flexDirection: "column", alignItems: "center", justifyContent: "center",
            gap: 16, padding: 26, textAlign: "center", background: "var(--bg-app)" }}>
            <div style={{ width: 54, height: 54, borderRadius: 15, display: "grid",
              placeItems: "center", background: "var(--blue)", color: "#fff" }}>
              <Icons.news size={28} /></div>
            <div>
              <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 17,
                color: "var(--text)" }}>Nambikkai News</div>
              <div style={{ fontFamily: "var(--ff-ui)", fontSize: 13.5,
                color: "var(--subtext)", marginTop: 5, lineHeight: 1.5, maxWidth: 240 }}>
                தமிழ் செய்திகள் · the latest from the Nambikkai newsroom.
              </div>
            </div>
            <a href={URL} target="_blank" rel="noopener noreferrer"
              style={{ display: "inline-flex", alignItems: "center", gap: 7,
                padding: "11px 18px", borderRadius: 11, background: "var(--blue)",
                color: "#fff", textDecoration: "none", fontFamily: "var(--ff-ui)",
                fontWeight: 600, fontSize: 14,
                boxShadow: "0 6px 16px rgba(0,68,187,0.28)" }}>
              Open nambikkai.com <Icons.arrowR size={15} />
            </a>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================ TERMS & CONDITIONS ============================
const TERMS_V2 = [
  ["1 · Accuracy & good faith",
    "I confirm the report is true to the best of my knowledge, based on what I witnessed or verified, and is not knowingly false, misleading, or fabricated."],
  ["2 · Original work & rights",
    "The text, photos, and video I submit are my own original work, or I hold the rights to share them. I grant Nambikkai a licence to review, edit, publish, and distribute this content across its platforms."],
  ["3 · No harmful content",
    "My submission contains no hate speech, harassment, defamation, graphic content without public-interest value, or material that endangers any individual's safety or privacy."],
  ["4 · Editorial review",
    "I understand every submission is reviewed by the editorial desk, may be edited for clarity, fact-checked, held, or declined, and that submitting does not guarantee publication."],
  ["5 · Location & personal data",
    "I consent to the location and contributor details attached to this report being used for verification. I have not included others' personal data without their consent."],
];

function TermsSheet({ resubmit, onAgree, onClose }) {
  const [agreed, setAgreed] = React.useState(false);
  return (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, zIndex: 95,
      display: "flex", flexDirection: "column", justifyContent: "flex-end",
      background: "color-mix(in srgb, #0a0f1a 50%, transparent)",
      animation: "nk-fade .18s ease" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ background: "var(--bg-app)",
        borderTopLeftRadius: 22, borderTopRightRadius: 22, maxHeight: "86%",
        display: "flex", flexDirection: "column",
        animation: "nk-slideup .26s cubic-bezier(.2,.8,.2,1)" }}>
        <div style={{ padding: "18px 20px 12px", borderBottom: "1px solid var(--border)" }}>
          <div style={{ display: "flex", alignItems: "center",
            justifyContent: "space-between" }}>
            <span style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 18,
              color: "var(--text)" }}>Contributor agreement</span>
            <button onClick={onClose} style={{ color: "var(--subtext)", background: "none",
              border: "none", cursor: "pointer", padding: 4 }}>
              <Icons.x size={20} /></button>
          </div>
          <div style={{ fontFamily: "var(--ff-ui)", fontSize: 13, color: "var(--subtext)",
            marginTop: 4 }}>
            Please review before {resubmit ? "resubmitting" : "submitting"} to the editorial desk.
          </div>
        </div>
        <div style={{ overflow: "auto", padding: "16px 20px", display: "flex",
          flexDirection: "column", gap: 15 }}>
          {TERMS_V2.map(([h, b]) => (
            <div key={h}>
              <div style={{ fontFamily: "var(--ff-ui)", fontWeight: 700, fontSize: 14,
                color: "var(--text)", marginBottom: 4 }}>{h}</div>
              <div style={{ fontFamily: "var(--ff-ui)", fontSize: 13.5, lineHeight: 1.55,
                color: "var(--text-2)" }}>{b}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: "12px 20px 26px", borderTop: "1px solid var(--border)",
          background: "var(--bg-card)" }}>
          <button onClick={() => setAgreed((a) => !a)} style={{ width: "100%", display: "flex",
            alignItems: "center", gap: 11, background: "none", border: "none",
            cursor: "pointer", padding: "4px 0 14px", textAlign: "left" }}>
            <span style={{ width: 24, height: 24, borderRadius: 7, flexShrink: 0,
              display: "grid", placeItems: "center", color: "#fff",
              background: agreed ? "var(--blue)" : "var(--bg-card)",
              border: `1.5px solid ${agreed ? "var(--blue)" : "var(--border-2)"}`,
              transition: "all .15s ease" }}>
              {agreed && <Icons.check size={15} sw={2.6} />}
            </span>
            <span style={{ fontFamily: "var(--ff-ui)", fontSize: 13.5, color: "var(--text)",
              lineHeight: 1.4 }}>I have read and agree to the contributor agreement.</span>
          </button>
          <div style={{ display: "flex", gap: 10 }}>
            <button onClick={onClose} style={{ flex: "0 0 auto", padding: "13px 18px",
              borderRadius: 11, background: "var(--bg-card)", color: "var(--text-2)",
              border: "1px solid var(--border-2)", fontFamily: "var(--ff-ui)",
              fontWeight: 600, fontSize: 14.5, cursor: "pointer" }}>Cancel</button>
            <button onClick={() => agreed && onAgree()} disabled={!agreed}
              style={{ flex: 1, padding: "13px", borderRadius: 11,
                fontFamily: "var(--ff-ui)", fontWeight: 600, fontSize: 15,
                color: "#fff", background: agreed ? "var(--blue)" : "var(--border-2)",
                border: "none", cursor: agreed ? "pointer" : "not-allowed",
                display: "flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
              {resubmit ? "Agree & resubmit" : "Agree & post"} <Icons.send size={16} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReportScreen, PostsScreen, HomeSiteScreen, TermsSheet, CATS_V2 });
