/* Interactive launch → go-live → first-revenue timeline */
const { useState: useStateT } = React;

const DAY = 86400000;
const addDays = (ms, d) => ms + d * DAY;
const fmtDate = (ms) =>
  new Date(ms).toLocaleDateString("vi-VN", { day: "numeric", month: "short", year: "numeric" });

const PATHS = {
  company: {
    note: "Thành lập công ty trước → tài khoản Organization. Bỏ qua 14 ngày testing nhưng cần chờ D-U-N-S.",
    steps: [
      { day: 0,   phase: "Chuẩn bị",       t: "Nộp hồ sơ thành lập công ty", d: "Đăng ký kinh doanh (~1–2 tuần)" },
      { day: 28,  phase: "Chuẩn bị",       t: "Có D-U-N-S Number", d: "Xin tại Dun & Bradstreet, có thể tới 30 ngày — làm song song" },
      { day: 30,  phase: "Chuẩn bị",       t: "Đăng ký Apple + Google", d: "Apple Org $99/năm · Google $25 · ký Paid Apps Agreement" },
      { day: 37,  phase: "Chuẩn bị",       t: "Mở tài khoản ngoại tệ + tax forms", d: "Techcombank/VCB/BIDV · W-8BEN" },
      { day: 50,  phase: "Build & Submit", t: "Hoàn tất IAP, privacy, test", d: "StoreKit/Billing, server validation, demo account" },
      { day: 53,  phase: "Build & Submit", t: "Submit review 2 store", d: "iOS 1–3 ngày · Android 1–7 ngày" },
      { day: 60,  phase: "Thu phí",        t: "GO-LIVE", d: "App lên store, bắt đầu bán subscription", kind: "golive" },
      { day: 63,  phase: "Thu phí",        t: "Hết trial 3 ngày → tính phí", d: "Bắt đầu phát sinh doanh thu thực" },
      { day: 105, phase: "Thu phí",        t: "Đồng đầu tiên về tài khoản", d: "Apple trả trong ~45 ngày sau cuối fiscal month", kind: "revenue" },
    ],
  },
  individual: {
    note: "Tài khoản cá nhân mới phải hoàn tất 14 ngày closed testing trên Google trước production.",
    steps: [
      { day: 0,  phase: "Chuẩn bị",       t: "Đăng ký Apple + Google", d: "Apple $99/năm · Google $25 một lần" },
      { day: 3,  phase: "Chuẩn bị",       t: "Hoàn thiện hồ sơ developer", d: "Ký Paid Apps Agreement, thông tin ngân hàng" },
      { day: 3,  phase: "Build & Submit", t: "Bắt đầu 14 ngày Closed Testing", d: "Bắt buộc · cần 12+ tester ngoài (Google Play)" },
      { day: 17, phase: "Build & Submit", t: "Hoàn tất testing + build app", d: "IAP, privacy, demo account sẵn sàng" },
      { day: 18, phase: "Build & Submit", t: "Submit production", d: "iOS 1–3 ngày · Android 1–7 ngày" },
      { day: 25, phase: "Thu phí",        t: "GO-LIVE", d: "App lên store, bắt đầu bán subscription", kind: "golive" },
      { day: 28, phase: "Thu phí",        t: "Hết trial 3 ngày → tính phí", d: "Bắt đầu phát sinh doanh thu thực" },
      { day: 72, phase: "Thu phí",        t: "Đồng đầu tiên về tài khoản", d: "Payout ~45 ngày sau cuối fiscal month" },
    ],
  },
};

const PHASE_COLORS = { "Chuẩn bị": "var(--taupe-deep)", "Build & Submit": "var(--ink-soft)", "Thu phí": "var(--accent)" };

function LaunchTimeline() {
  const today = Math.floor(Date.now() / DAY) * DAY;
  const [account, setAccount] = useStateT("company");
  const [offset, setOffset] = useStateT(14); // days from today
  const startMs = addDays(today, offset);

  const path = PATHS[account];
  const goLive = path.steps.find((s) => s.kind === "golive");
  const revenue = path.steps.find((s) => s.kind === "revenue") || path.steps[path.steps.length - 1];

  const onDate = (e) => {
    const v = new Date(e.target.value).getTime();
    if (!isNaN(v)) setOffset(Math.max(0, Math.round((v - today) / DAY)));
  };
  const isoStart = new Date(startMs).toISOString().slice(0, 10);

  return (
    <section className="section" id="timeline" style={{ paddingTop: 0 }}>
      <div className="wrap">
        <SecHead num="05" eyebrow="Công cụ · Lộ trình ra mắt"
          title="Từ hôm nay đến <span class='serif-it' style='color:var(--accent)'>đồng đầu tiên</span>"
          lede="Chọn loại tài khoản và kéo ngày bắt đầu để xem khi nào app go-live và khi nào tiền thực sự về tài khoản." />

        <div className="tool" style={{ overflow: "hidden" }}>
          {/* controls */}
          <div style={{ padding: "clamp(20px,3vw,30px)", borderBottom: "1px solid var(--line)", display: "grid", gap: 20 }}>
            <div className="row between center" style={{ flexWrap: "wrap", gap: 12 }}>
              <span className="tool-tag"><span className="dot"></span>Loại tài khoản</span>
              <Segmented accent value={account} onChange={setAccount}
                options={[{ value: "individual", label: "Cá nhân" }, { value: "company", label: "Doanh nghiệp" }]} />
            </div>
            <div className="field">
              <div className="field-lab">
                <span className="nm">Ngày bắt đầu</span>
                <input type="date" className="numinput" style={{ width: "auto", padding: "5px 10px", fontSize: 13 }} value={isoStart} onChange={onDate} />
              </div>
              <input type="range" min={0} max={240} step={1} value={offset} onChange={(e) => setOffset(parseInt(e.target.value))} />
              <div className="row between mono small muted" style={{ letterSpacing: ".04em" }}>
                <span>Hôm nay</span><span>+8 tháng</span>
              </div>
            </div>
            <p className="small muted" style={{ margin: 0 }}>{path.note}</p>
          </div>

          {/* outcome cards */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", borderBottom: "1px solid var(--line)" }} className="outcome-grid">
            {[
              { lab: "Go-live", ms: addDays(startMs, goLive.day), days: goLive.day, c: "var(--ink)" },
              { lab: "Bắt đầu thu phí", ms: addDays(startMs, goLive.day + 3), days: goLive.day + 3, c: "var(--ink)" },
              { lab: "Đồng đầu tiên về tài khoản", ms: addDays(startMs, revenue.day), days: revenue.day, c: "var(--accent)" },
            ].map((o, i) => (
              <div key={i} style={{ padding: "20px 22px", borderRight: i < 2 ? "1px solid var(--line)" : "none" }}>
                <p className="mono" style={{ fontSize: 10.5, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--ink-mute)", margin: "0 0 8px" }}>{o.lab}</p>
                <div className="num" style={{ fontFamily: "var(--serif)", fontSize: "clamp(20px,2.6vw,28px)", color: o.c, lineHeight: 1 }}>{fmtDate(o.ms)}</div>
                <p className="num small muted" style={{ margin: "6px 0 0" }}>≈ {o.days} ngày kể từ bắt đầu</p>
              </div>
            ))}
          </div>

          {/* vertical timeline */}
          <div style={{ padding: "clamp(24px,4vw,40px) clamp(20px,4vw,40px)" }}>
            <div style={{ position: "relative", paddingLeft: 30 }}>
              <div style={{ position: "absolute", left: 5, top: 6, bottom: 6, width: 2, background: "var(--line)" }} />
              {path.steps.map((s, i) => {
                const big = s.kind === "golive" || s.kind === "revenue";
                const col = s.kind === "revenue" ? "var(--accent)" : s.kind === "golive" ? "var(--green)" : PHASE_COLORS[s.phase];
                return (
                  <div key={i} style={{ position: "relative", paddingBottom: i < path.steps.length - 1 ? 26 : 0 }}>
                    <div style={{ position: "absolute", left: -30, top: 3, width: 12, height: 12, borderRadius: "50%",
                      background: big ? col : "var(--paper-2)", border: `2px solid ${col}`, transform: big ? "scale(1.25)" : "none", boxShadow: big ? `0 0 0 4px var(--paper-2)` : "none" }} />
                    <div className="row between" style={{ gap: 16, flexWrap: "wrap" }}>
                      <div style={{ flex: "1 1 240px" }}>
                        <div className="row center" style={{ gap: 10, flexWrap: "wrap" }}>
                          <span style={{ fontSize: big ? 18 : 15.5, fontWeight: big ? 600 : 500, fontFamily: big ? "var(--serif)" : "var(--sans)",
                            color: s.kind === "revenue" ? "var(--accent)" : "var(--ink)" }}>{s.t}</span>
                          {big && <span className="mono" style={{ fontSize: 9.5, letterSpacing: ".1em", textTransform: "uppercase", padding: "2px 8px", borderRadius: 100,
                            background: s.kind === "revenue" ? "var(--accent)" : "var(--green)", color: "#fff" }}>{s.kind === "revenue" ? "Tiền về" : "Live"}</span>}
                        </div>
                        <p className="small muted" style={{ margin: "3px 0 0" }}>{s.d}</p>
                      </div>
                      <div style={{ textAlign: "right", minWidth: 110 }}>
                        <div className="num" style={{ fontSize: 14, color: "var(--ink)" }}>{fmtDate(addDays(startMs, s.day))}</div>
                        <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-faint)", letterSpacing: ".05em" }}>NGÀY +{s.day}</div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
        <p className="small muted" style={{ marginTop: 16, maxWidth: "70ch" }}>
          Ước tính lộ trình điển hình. Các mốc có thể chạy song song — D-U-N-S, build app và mở tài khoản ngân hàng thường làm cùng lúc. Thời gian review và payout tùy từng trường hợp.
        </p>
      </div>
    </section>
  );
}

Object.assign(window, { LaunchTimeline });
