/* ===== Trash bin: deleted tasks (30-day retention) + PIN gate ===== */
const { useState: useStateTR, useEffect: useEffectTR, useMemo: useMemoTR } = React;

const TRASH_RETENTION_DAYS = 30;
const REAL_DAY_MS = 86400000;

function hashPin(pin) {
  // djb2 + salt — not cryptographically strong, but avoids plaintext storage
  let h = 5381;
  const s = pin + "::teamflow_v1::salt";
  for (let i = 0; i < s.length; i++) {
    h = ((h << 5) + h) + s.charCodeAt(i);
    h = h | 0;
  }
  return (h >>> 0).toString(36);
}

function trashDaysLeft(deletedAt) {
  const elapsed = (Date.now() - deletedAt) / REAL_DAY_MS;
  return Math.max(0, Math.ceil(TRASH_RETENTION_DAYS - elapsed));
}
function trashDaysSince(deletedAt) {
  return Math.max(0, Math.floor((Date.now() - deletedAt) / REAL_DAY_MS));
}
function fmtTrashAgo(deletedAt) {
  const d = trashDaysSince(deletedAt);
  if (d === 0) return "วันนี้";
  if (d === 1) return "เมื่อวาน";
  return `${d} วันก่อน`;
}

function TrashModal({ trash, members, pinHash, onClose, onRestore, onPermDelete, onEmpty, onSetPin }) {
  const [pending, setPending] = useStateTR(null); // {type:'one'|'all', id?}
  const [pinInput, setPinInput] = useStateTR("");
  const [pinErr, setPinErr] = useStateTR("");
  const [setupStage, setSetupStage] = useStateTR(null); // null | 'set' | 'confirm'
  const [setup1, setSetup1] = useStateTR("");

  useEffectTR(() => {
    const onKey = (e) => { if (e.key === "Escape") { if (pending) cancelPin(); else onClose(); } };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [pending]);

  const memberMap = useMemoTR(() => Object.fromEntries(members.map(m => [m.id, m])), [members]);

  const sorted = [...trash].sort((a, b) => b.deletedAt - a.deletedAt);

  const startPerm = (id) => {
    setPending({ type: "one", id });
    setPinInput(""); setPinErr("");
    if (!pinHash) { setSetupStage("set"); setSetup1(""); }
  };
  const startEmpty = () => {
    if (!trash.length) return;
    setPending({ type: "all" });
    setPinInput(""); setPinErr("");
    if (!pinHash) { setSetupStage("set"); setSetup1(""); }
  };
  const cancelPin = () => {
    setPending(null); setPinInput(""); setPinErr("");
    setSetupStage(null); setSetup1("");
  };

  const completeAction = () => {
    if (pending.type === "one") onPermDelete(pending.id);
    else onEmpty();
    cancelPin();
  };

  const verifyAndAct = () => {
    if (pinInput.length < 4) { setPinErr("PIN ต้องมีอย่างน้อย 4 หลัก"); return; }
    if (hashPin(pinInput) !== pinHash) { setPinErr("PIN ไม่ถูกต้อง"); return; }
    completeAction();
  };

  const handleSetup = () => {
    if (setupStage === "set") {
      if (!/^\d{4,6}$/.test(pinInput)) { setPinErr("ใส่ตัวเลข 4–6 หลัก"); return; }
      setSetup1(pinInput); setPinInput(""); setPinErr(""); setSetupStage("confirm");
    } else {
      if (pinInput !== setup1) { setPinErr("PIN ไม่ตรงกัน ลองใหม่อีกครั้ง"); setPinInput(""); return; }
      const h = hashPin(pinInput);
      onSetPin(h);
      // proceed with the original action
      if (pending.type === "one") onPermDelete(pending.id);
      else onEmpty();
      cancelPin();
    }
  };

  // PIN sheet (modal-within-modal)
  const showPinGate = !!pending;

  return (
    <div style={trStyles.overlay} onMouseDown={onClose}>
      <div style={trStyles.sheet} className="scroll modal-sheet" onMouseDown={(e) => e.stopPropagation()}>
        <div style={trStyles.head}>
          <div>
            <div style={trStyles.kicker}>ถังขยะ · Trash</div>
            <div style={trStyles.headTitle}>งานที่ถูกลบ</div>
            <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>
              เก็บไว้ {TRASH_RETENTION_DAYS} วัน · กู้คืนได้ตลอด · หลังจากนั้นจะลบอัตโนมัติ
            </div>
          </div>
          <button style={trStyles.x} className="tm-x" onClick={onClose}><CloseIcon /></button>
        </div>

        <div style={trStyles.body}>
          {sorted.length === 0 ? (
            <div style={trStyles.empty}>
              <div style={trStyles.emptyIcon}><TrashIcon /></div>
              <div style={{ fontSize: 15, fontWeight: 600, color: "var(--ink-2)", marginTop: 10 }}>ถังขยะว่างเปล่า</div>
              <div style={{ fontSize: 13, color: "var(--ink-3)", marginTop: 4 }}>งานที่ลบจะมาแสดงที่นี่</div>
            </div>
          ) : (
            <>
              <div style={trStyles.list}>
                {sorted.map(t => {
                  const m = memberMap[t.assignee];
                  const left = trashDaysLeft(t.deletedAt);
                  const urgent = left <= 5;
                  const p = PRIORITY_MAP[t.priority];
                  const st = STATUS_MAP[t.status];
                  return (
                    <div key={t.id} style={trStyles.row}>
                      <div style={{ ...trStyles.pBar, background: p ? p.color : "var(--ink-3)" }}></div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
                          <span style={trStyles.title}>{t.title}</span>
                        </div>
                        <div style={{ display: "flex", gap: 14, fontSize: 12, color: "var(--ink-3)", alignItems: "center", flexWrap: "wrap" }}>
                          {m && (
                            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                              <Avatar member={m} size={18} /> {m.nick}
                            </span>
                          )}
                          {st && (
                            <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                              <span className="dot" style={{ background: st.color }}></span> {st.label}
                            </span>
                          )}
                          <span>ลบ {fmtTrashAgo(t.deletedAt)}</span>
                        </div>
                      </div>
                      <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 7 }}>
                        <span style={{
                          fontSize: 11, fontWeight: 700,
                          color: urgent ? "var(--high)" : "var(--ink-3)",
                          background: urgent ? "var(--high-soft)" : "var(--surface-soft)",
                          padding: "2px 9px", borderRadius: 20,
                        }}>เหลือ {left} วัน</span>
                        <div style={{ display: "flex", gap: 6 }}>
                          <button className="btn btn-soft" style={trStyles.smallBtn} onClick={() => onRestore(t.id)}>
                            ↺ กู้คืน
                          </button>
                          <button className="btn" style={{ ...trStyles.smallBtn, background: "var(--high-soft)", color: "var(--high)" }}
                            title="ลบถาวร (ต้องใส่ PIN)" onClick={() => startPerm(t.id)}>
                            <TrashIcon />
                          </button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>

              <div style={trStyles.foot}>
                <span style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{sorted.length} รายการในถังขยะ</span>
                <button className="btn" style={{ background: "var(--high)", color: "#fff", padding: "9px 14px", fontSize: 13 }} onClick={startEmpty}>
                  <TrashIcon /> เทถังขยะทั้งหมด
                </button>
              </div>
            </>
          )}
        </div>

        {showPinGate && (
          <div style={trStyles.gateOverlay} onMouseDown={cancelPin}>
            <div style={trStyles.gateSheet} onMouseDown={(e) => e.stopPropagation()}>
              {setupStage ? (
                <>
                  <div style={trStyles.gateIcon}><LockIcon /></div>
                  <div style={trStyles.gateTitle}>
                    {setupStage === "set" ? "ตั้งรหัส PIN" : "ยืนยัน PIN อีกครั้ง"}
                  </div>
                  <div style={trStyles.gateSub}>
                    {setupStage === "set"
                      ? "ใช้รหัสนี้ทุกครั้งที่ลบงานถาวร · 4–6 หลัก · เก็บแบบ hash ในเครื่องเท่านั้น"
                      : "พิมพ์ PIN เดิมอีกครั้งเพื่อยืนยัน"}
                  </div>
                  <PinField value={pinInput} onChange={(v) => { setPinInput(v); setPinErr(""); }} onSubmit={handleSetup} />
                  {pinErr && <div style={trStyles.gateErr}>{pinErr}</div>}
                  <div style={{ display: "flex", gap: 10, marginTop: 18, justifyContent: "flex-end" }}>
                    <button className="btn btn-ghost" onClick={cancelPin}>ยกเลิก</button>
                    <button className="btn btn-primary" onClick={handleSetup}>
                      {setupStage === "set" ? "ถัดไป" : "ยืนยัน"}
                    </button>
                  </div>
                </>
              ) : (
                <>
                  <div style={trStyles.gateIcon}><LockIcon /></div>
                  <div style={trStyles.gateTitle}>ใส่รหัส PIN</div>
                  <div style={trStyles.gateSub}>
                    {pending.type === "all"
                      ? `กำลังจะลบถาวร ${trash.length} งาน · ไม่สามารถกู้คืนได้`
                      : "การลบถาวรไม่สามารถกู้คืนได้"}
                  </div>
                  <PinField value={pinInput} onChange={(v) => { setPinInput(v); setPinErr(""); }} onSubmit={verifyAndAct} />
                  {pinErr && <div style={trStyles.gateErr}>{pinErr}</div>}
                  <div style={{ display: "flex", gap: 10, marginTop: 18, justifyContent: "flex-end" }}>
                    <button className="btn btn-ghost" onClick={cancelPin}>ยกเลิก</button>
                    <button className="btn" style={{ background: "var(--high)", color: "#fff" }} onClick={verifyAndAct}>
                      ยืนยันลบถาวร
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

/* ---- PIN input: 6 boxes ---- */
function PinField({ value, onChange, onSubmit }) {
  const max = 6;
  const ref = React.useRef(null);
  useEffectTR(() => { ref.current && ref.current.focus(); }, []);
  return (
    <div style={trStyles.pinWrap}>
      <input ref={ref} type="password" inputMode="numeric" pattern="[0-9]*" maxLength={max}
        value={value}
        onChange={(e) => onChange(e.target.value.replace(/\D/g, "").slice(0, max))}
        onKeyDown={(e) => { if (e.key === "Enter") onSubmit(); }}
        style={trStyles.pinInput} autoFocus />
      <div style={trStyles.pinDots} onClick={() => ref.current && ref.current.focus()}>
        {Array.from({ length: max }).map((_, i) => {
          const filled = i < value.length;
          return (
            <div key={i} style={{
              width: 38, height: 46, borderRadius: 10,
              border: "2px solid " + (filled ? "var(--primary)" : "var(--line)"),
              background: filled ? "var(--primary-soft)" : "var(--surface)",
              display: "grid", placeItems: "center",
              fontSize: 22, fontWeight: 700, color: "var(--primary)", fontFamily: "var(--font-num)",
              transition: ".12s",
            }}>{filled ? "•" : ""}</div>
          );
        })}
      </div>
    </div>
  );
}

function LockIcon() {
  return (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <rect x="4" y="10" width="16" height="11" rx="2.5" stroke="currentColor" strokeWidth="2"/>
      <path d="M8 10V7a4 4 0 018 0v3" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
      <circle cx="12" cy="15.5" r="1.3" fill="currentColor"/>
    </svg>
  );
}

const trStyles = {
  overlay: {
    position: "fixed", inset: 0, zIndex: 110, background: "rgba(20,30,55,.42)",
    backdropFilter: "blur(4px)", display: "grid", placeItems: "center", padding: 20,
    animation: "overlayIn .2s ease both",
  },
  sheet: {
    width: "min(640px, 100%)", maxHeight: "92vh", overflowY: "auto",
    background: "var(--surface)", borderRadius: 22, boxShadow: "var(--shadow-pop)",
    animation: "sheetIn .3s cubic-bezier(.2,.7,.3,1) both",
    position: "relative",
  },
  head: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", padding: "24px 26px 8px" },
  kicker: { fontSize: 12, fontWeight: 700, color: "var(--primary)", letterSpacing: ".3px", textTransform: "uppercase" },
  headTitle: { fontSize: 21, fontWeight: 700, marginTop: 4 },
  x: { width: 36, height: 36, borderRadius: 10, border: "1px solid var(--line)", background: "var(--surface)", color: "var(--ink-2)", display: "grid", placeItems: "center" },
  body: { padding: "10px 26px 22px" },
  list: { display: "flex", flexDirection: "column", gap: 8 },
  row: {
    display: "flex", alignItems: "center", gap: 12, padding: "12px 14px",
    background: "var(--surface-soft)", borderRadius: 13, border: "1px solid var(--line-soft)",
  },
  pBar: { width: 4, alignSelf: "stretch", borderRadius: 4, flex: "none" },
  title: { fontWeight: 600, fontSize: 14.5, color: "var(--ink)" },
  smallBtn: { padding: "7px 11px", fontSize: 12.5 },
  empty: {
    textAlign: "center", padding: "48px 20px",
    background: "var(--surface-soft)", borderRadius: 14, border: "1.5px dashed var(--line)",
  },
  emptyIcon: {
    width: 56, height: 56, borderRadius: 14, margin: "0 auto",
    background: "var(--surface)", color: "var(--ink-3)",
    display: "grid", placeItems: "center", boxShadow: "var(--shadow-sm)",
  },
  foot: {
    display: "flex", justifyContent: "space-between", alignItems: "center",
    marginTop: 16, paddingTop: 14, borderTop: "1px solid var(--line-soft)",
  },
  gateOverlay: {
    position: "absolute", inset: 0, borderRadius: 22,
    background: "rgba(22,35,63,.55)", backdropFilter: "blur(6px)",
    display: "grid", placeItems: "center", padding: 20, zIndex: 5,
    animation: "overlayIn .15s ease both",
  },
  gateSheet: {
    width: "min(420px, 100%)", background: "var(--surface)",
    borderRadius: 18, boxShadow: "var(--shadow-pop)", padding: "26px 26px 24px",
    animation: "sheetIn .25s cubic-bezier(.2,.7,.3,1) both",
  },
  gateIcon: {
    width: 48, height: 48, borderRadius: 14, background: "var(--high-soft)", color: "var(--high)",
    display: "grid", placeItems: "center", marginBottom: 14,
  },
  gateTitle: { fontSize: 18, fontWeight: 700, color: "var(--ink)" },
  gateSub: { fontSize: 13, color: "var(--ink-3)", marginTop: 6, lineHeight: 1.5 },
  gateErr: { fontSize: 12.5, color: "var(--high)", fontWeight: 600, marginTop: 10 },
  pinWrap: { position: "relative", marginTop: 16 },
  pinInput: {
    position: "absolute", inset: 0, opacity: 0, border: 0, padding: 0,
    width: "100%", height: "100%", cursor: "pointer",
  },
  pinDots: { display: "flex", gap: 7, justifyContent: "center" },
};

window.TrashModal = TrashModal;
window.hashPin = hashPin;
window.TRASH_RETENTION_DAYS = TRASH_RETENTION_DAYS;
window.REAL_DAY_MS = REAL_DAY_MS;
