// ADM-PROC-08 · Broadcast — preview & send (AMOMS Module 1)
// Admin Web · Procurement Manager · P0 · 1440×900
// Components: C-019 Tab bar · C-124 Stepper · C-008 Time-slot picker · C-108 Modal · C-001 Button
// Registered as window.Pages.broadcastPreview

const Ic8 = window.Icons;
const REQ_08 = { id: "PR-2026-0184", product: "Hass", qty: 28000, rate: 95, deadline: "17 May" };
const RECIPIENTS_08 = { App: 142, SMS: 139, WhatsApp: 96 };
const SAMPLE_FARMERS = window.MD.FARMERS.slice(0, 5);

const renderMsg = (name) => `Hello ${name}, AMOMS needs ${REQ_08.qty.toLocaleString("en-US")} kg of ${REQ_08.product} avocados at up to KSh ${REQ_08.rate}/kg. Respond by ${REQ_08.deadline} to be considered.`;

const BroadcastPreview = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const tweakState = (tweaks && tweaks.sendState) || "ready";

  const [tab, setTab] = useState("App");
  const [sampleIdx, setSampleIdx] = useState(0);
  const [schedule, setSchedule] = useState(tweakState === "scheduled" ? "later" : "now");
  const [recipOpen, setRecipOpen] = useState(false);
  const [confirmOpen, setConfirmOpen] = useState(false);
  // runtime send phase: idle | sending | sent | partial
  const [phase, setPhase] = useState(tweakState === "sending" ? "sending" : tweakState === "sent" ? "sent" : tweakState === "partial" ? "partial" : "idle");
  const [progress, setProgress] = useState(tweakState === "sending" ? 40 : 0);
  useEffect(() => { setPhase(tweakState === "sending" ? "sending" : tweakState === "sent" ? "sent" : tweakState === "partial" ? "partial" : "idle"); setSchedule(tweakState === "scheduled" ? "later" : "now"); }, [tweakState]);

  const totalFarmers = 142;
  const channelCount = 3;
  const smsCost = RECIPIENTS_08.SMS * 1.2; // KSh per SMS
  const sample = SAMPLE_FARMERS[sampleIdx];

  const doSend = () => {
    setConfirmOpen(false);
    setPhase("sending"); setProgress(8);
    const t = setInterval(() => setProgress(p => {
      const np = p + 14;
      if (np >= 100) { clearInterval(t); setTimeout(() => setPhase("sent"), 350); return 100; }
      return np;
    }), 260);
  };

  const sendLabel = schedule === "later" ? "Schedule broadcast" : "Send broadcast";

  return (
    <div className="page bp-page">
      <div className="bp-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-07.html")}><Ic8.ChevronLeft size={18} /></button>
        <div className="bp-head-title">
          <h1 className="bp-title">Preview &amp; send — <span className="mono" style={{ fontWeight: 600 }}>{REQ_08.id}</span></h1>
          <div className="bp-sub">Review the exact message each farmer receives.</div>
        </div>
        <div className="bp-steps">
          <span className="bp-stepi done"><span className="num"><Ic8.Check size={12} /></span>Select farmers</span>
          <span className="bp-step-line" />
          <span className="bp-stepi on"><span className="num">2</span>Preview &amp; send</span>
        </div>
        <div className="bp-head-actions">
          <Button variant="outline" onClick={() => go("ADM-PROC-07.html")}>Back</Button>
          <Button variant="destructive" icon={schedule === "later" ? Ic8.Clock : Ic8.Bolt}
            onClick={() => (totalFarmers >= 500 || schedule === "later") ? setConfirmOpen(true) : doSend()}>{sendLabel}</Button>
        </div>
      </div>

      {/* Summary strip */}
      <div className="bp-summary">
        <div className="bp-stat"><div className="bp-stat-lab"><Ic8.Users size={13} />Recipients</div><div className="bp-stat-val">{totalFarmers}</div></div>
        <div className="bp-stat"><div className="bp-stat-lab"><Ic8.Bolt size={13} />Channels</div><div className="bp-stat-val">{channelCount}</div></div>
        <div className="bp-stat"><div className="bp-stat-lab"><Ic8.Coin size={13} />Est. SMS cost</div><div className="bp-stat-val">KSh {Math.round(smsCost).toLocaleString("en-US")}</div></div>
        <div className="bp-stat"><div className="bp-stat-lab"><Ic8.Clock size={13} />Send time</div><div className="bp-stat-val" style={{ fontSize: 15 }}>{schedule === "later" ? "Today 16:00" : "Immediately"}</div></div>
      </div>

      <div className="bp-grid">
        {/* Preview */}
        <Card>
          <div className="card-head" style={{ alignItems: "center" }}>
            <Tabs value={tab} onChange={setTab} options={[{ value: "App", label: "App" }, { value: "SMS", label: "SMS" }, { value: "WhatsApp", label: "WhatsApp" }]} />
            <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 8 }}>
              <span className="muted" style={{ fontSize: 12 }}>Preview as</span>
              <select className="select" style={{ width: "auto", height: 30, fontSize: 12.5 }} value={sampleIdx} onChange={(e) => setSampleIdx(Number(e.target.value))}>
                {SAMPLE_FARMERS.map((f, i) => <option key={f.id} value={i}>{f.name}</option>)}
              </select>
            </div>
          </div>
          <div className="card-body">
            <div className="bp-preview-wrap">
              <div className="bp-device">
                <div className="bp-device-bar"><div className="bp-device-notch" /></div>
                {tab === "App" && (
                  <>
                    <div className="bp-app-top"><span className="bp-app-mark"><Ic8.Leaf size={12} /></span><span style={{ fontSize: 13, fontWeight: 600 }}>AMOMS</span></div>
                    <div className="bp-app-body">
                      <div className="bp-push">
                        <div className="bp-push-head"><Ic8.Leaf size={11} />AMOMS · now</div>
                        <div className="bp-push-title">New buying request — {REQ_08.product}</div>
                        <div className="bp-push-body">{renderMsg(sample.name)}</div>
                      </div>
                    </div>
                  </>
                )}
                {tab === "SMS" && (
                  <div className="bp-sms">
                    <div className="bp-sms-meta">AMOMS · SMS · now</div>
                    <div className="bp-bubble">{renderMsg(sample.name)}</div>
                    <div className="bp-sms-meta">Reply YES to register interest</div>
                  </div>
                )}
                {tab === "WhatsApp" && (
                  <>
                    <div className="bp-wa-top"><span className="bp-app-mark"><Ic8.Leaf size={12} /></span><span style={{ fontSize: 13, fontWeight: 600 }}>AMOMS</span><span style={{ marginLeft: "auto", fontSize: 10.5, opacity: 0.85 }}>Business</span></div>
                    <div className="bp-sms" style={{ background: "oklch(0.95 0.02 150)" }}>
                      <div className="bp-bubble wa">{renderMsg(sample.name)}</div>
                      <div className="bp-sms-meta">Tap to respond in WhatsApp</div>
                    </div>
                  </>
                )}
              </div>
            </div>

            {/* Recipient list (collapsible) */}
            <button className="proc-collapse-head" style={{ padding: "14px 2px 4px" }} onClick={() => setRecipOpen(o => !o)}>
              <div className="head-text"><div className="card-title" style={{ fontSize: 13.5 }}>Recipient summary</div></div>
              <Ic8.ChevronDown size={16} style={{ transition: "transform .2s", transform: recipOpen ? "rotate(180deg)" : "none", color: "var(--muted-foreground)" }} />
            </button>
            {recipOpen && (
              <div style={{ paddingTop: 4 }}>
                {Object.entries(RECIPIENTS_08).map(([k, v]) => (
                  <div key={k} className="bp-recip-row"><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>{k === "App" ? <Ic8.Mobile size={14} /> : k === "SMS" ? <Ic8.Phone size={14} /> : <Ic8.Mail size={14} />}{k}</span><b>{v} farmers</b></div>
                ))}
              </div>
            )}
          </div>
        </Card>

        {/* Schedule */}
        <Card>
          <CardHead title="Schedule" desc="When the broadcast goes out." />
          <div className="card-body" style={{ paddingTop: 2 }}>
            <div className={`bp-radio-row${schedule === "now" ? " on" : ""}`} onClick={() => setSchedule("now")}>
              <span className="bp-radio-dot" />
              <div><div style={{ fontSize: 13, fontWeight: 500 }}>Send immediately</div><div className="muted" style={{ fontSize: 11.5 }}>Farmers receive it within a minute.</div></div>
            </div>
            <div className={`bp-radio-row${schedule === "later" ? " on" : ""}`} onClick={() => setSchedule("later")}>
              <span className="bp-radio-dot" />
              <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 500 }}>Schedule for later</div><div className="muted" style={{ fontSize: 11.5 }}>Min 5 minutes from now.</div></div>
            </div>
            {schedule === "later" && (
              <div className="field" style={{ marginTop: 6 }}>
                <label className="label">Send at</label>
                <input type="datetime-local" className="input" defaultValue="2026-05-12T16:00" />
                <div className="field-hint">Cancellable up to 5 minutes before send.</div>
              </div>
            )}
            <div className="alert" style={{ marginTop: 14, background: "var(--surface)" }}>
              <span className="alert-icon" style={{ color: "var(--muted-foreground)" }}><Ic8.Info size={15} /></span>
              <div className="alert-body"><div className="alert-desc">A failure on one channel never blocks the others. You'll see per-farmer delivery on the status screen.</div></div>
            </div>
          </div>
        </Card>
      </div>

      {/* Partial-failure banner (tweak) */}
      {phase === "partial" && (
        <div className="alert alert-warning" style={{ marginTop: 16 }}>
          <span className="alert-icon"><Ic8.Warning size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">Some messages failed to send</div>
            <div className="alert-desc">11 SMS failed (invalid numbers). App &amp; WhatsApp delivered. <a href="#" onClick={(e) => { e.preventDefault(); go("ADM-PROC-09.html"); }} style={{ color: "var(--soil)", fontWeight: 600 }}>View status &amp; retry →</a></div>
          </div>
        </div>
      )}

      {/* Confirmation modal */}
      <Modal open={confirmOpen} onClose={() => setConfirmOpen(false)} title={schedule === "later" ? "Schedule this broadcast?" : "Send to 142 farmers?"} sub={`${REQ_08.product} · ${REQ_08.qty.toLocaleString("en-US")} kg`}
        footer={<>
          <Button variant="outline" onClick={() => setConfirmOpen(false)}>Back</Button>
          <Button variant="primary" icon={Ic8.Bolt} onClick={doSend}>{schedule === "later" ? "Schedule" : "Send now"}</Button>
        </>}>
        <div style={{ fontSize: 13, lineHeight: 1.5 }}>
          This reaches <b>142 farmers</b> across <b>App, SMS &amp; WhatsApp</b>. Estimated SMS cost <b>KSh {Math.round(smsCost).toLocaleString("en-US")}</b>. {schedule === "later" ? "It will go out at the scheduled time and can be cancelled up to 5 minutes before." : "Sending starts immediately."}
        </div>
      </Modal>

      {/* Sending overlay */}
      {phase === "sending" && (
        <div className="bp-overlay">
          <div className="bp-modal">
            <div className="bp-spinner" />
            <div style={{ fontSize: 16, fontWeight: 600 }}>Broadcasting…</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 4 }}>Queuing messages across channels</div>
            <div className="bp-progressbar"><div style={{ width: progress + "%" }} /></div>
            <div className="muted" style={{ fontSize: 11.5 }}>{progress}% · cancel available for ~30s</div>
            <Button variant="outline" size="sm" style={{ marginTop: 14 }} onClick={() => { setPhase("idle"); setProgress(0); go("ADM-PROC-07.html"); }}>Cancel send</Button>
          </div>
        </div>
      )}

      {/* Success overlay */}
      {phase === "sent" && (
        <div className="bp-overlay">
          <div className="bp-modal">
            <div className="bp-success-ic"><Ic8.CheckCircle size={30} /></div>
            <div style={{ fontSize: 17, fontWeight: 600 }}>{schedule === "later" ? "Broadcast scheduled" : "Broadcast sent"}</div>
            <div className="muted" style={{ fontSize: 12.5, marginTop: 4, lineHeight: 1.5 }}>{REQ_08.id} is now <b>Broadcasted</b>. 142 farmers will see it across App, SMS &amp; WhatsApp.</div>
            <div className="row" style={{ justifyContent: "center", marginTop: 18 }}>
              <Button variant="outline" onClick={() => go("ADM-PROC-05.html")}>Back to requirement</Button>
              <Button variant="primary" icon={Ic8.Eye} onClick={() => go("ADM-PROC-09.html")}>View status</Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { broadcastPreview: BroadcastPreview });
