/* ============================================================================
   HOME — trip dashboard: hero, countdown, progress, quick actions, route.
   ============================================================================ */
function HomeScreen({ state, go, openAddExpense }) {
  const T = window.TRIP;
  const visited = state.places.filter((p) => p.visited).length;
  const totalPlaces = state.places.length;
  const spent = state.expenses.reduce((s, e) => s + e.vnd, 0);
  const photos = state.filledPhotos;

  const now = new Date();
  const depart = new Date(T.meta.departISO);
  const msDay = 86400000;
  const daysToGo = Math.ceil((depart - now) / msDay);
  const countdownLabel = daysToGo > 0 ? `in ${daysToGo} day${daysToGo === 1 ? "" : "s"}` : "happening now";

  // --- where are we in the trip? (local date vs the itinerary day dates) ---
  const todayISO = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
  const tripDays = T.meta.tripDays || [];
  const todayIdx = tripDays.findIndex((d) => d.iso === todayISO);
  const onTrip = todayIdx >= 0;
  const todayDayStr = onTrip ? tripDays[todayIdx].day : null;
  const isDepartDay = todayISO === (T.meta.departISO || "").slice(0, 10);
  const afterTrip = tripDays.length > 0 && todayISO > tripDays[tripDays.length - 1].iso;
  const TIME_ORDER = { Morning: 0, Afternoon: 1, Evening: 2, Night: 3 };
  const todayPlaces = onTrip
    ? state.places.filter((p) => p.day === todayDayStr).sort((a, b) => (TIME_ORDER[a.time] ?? 9) - (TIME_ORDER[b.time] ?? 9))
    : [];

  const actions = [
    { icon: "wallet", label: "Add expense", tone: "var(--color-teal)", onClick: openAddExpense },
    { icon: "image_add", label: "Add photo", tone: "var(--color-pumpkin)", onClick: () => go("photos") },
    { icon: "shield_keyhole", label: "Documents", tone: "var(--color-grape)", onClick: () => go("vault") },
    { icon: "sparkle", label: "Trip recap", tone: "var(--color-marigold)", onClick: () => go("recap") },
  ];

  return (
    <div>
      {/* ---------- HERO ---------- */}
      <div style={{
        position: "relative", overflow: "hidden",
        padding: "30px 20px 26px",
        background: "linear-gradient(150deg, var(--color-darkTeal) 0%, var(--color-teal) 62%, #0a9ca0 100%)",
        color: "#fff",
      }}>
        {/* lantern dots motif */}
        <div style={{ position: "absolute", inset: 0, opacity: 0.5, pointerEvents: "none",
          background: "radial-gradient(circle at 86% 14%, rgba(234,163,0,0.55) 0 8px, transparent 9px), radial-gradient(circle at 70% 8%, rgba(255,140,0,0.4) 0 5px, transparent 6px), radial-gradient(circle at 94% 34%, rgba(234,163,0,0.35) 0 5px, transparent 6px)" }} />
        <div style={{ position: "relative", display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <Overline color="rgba(255,255,255,0.72)">Friends trip · 2026</Overline>
            <div style={{ marginTop: 6 }}>
              <Serif size={46} weight={700} color="#fff" style={{ letterSpacing: "-0.02em" }}>{state.tripTitle || "Việt Nam"}</Serif>
            </div>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => go("settings")} title="Settings" style={{
              width: 40, height: 40, borderRadius: 12, border: "1px solid rgba(255,255,255,0.28)",
              background: "rgba(255,255,255,0.14)", display: "inline-flex", alignItems: "center",
              justifyContent: "center", cursor: "pointer", backdropFilter: "blur(4px)",
            }}>
              <Icon name="settings" size={20} color="#fff" />
            </button>
            <button onClick={() => go("vault")} title="Documents" style={{
              width: 40, height: 40, borderRadius: 12, border: "1px solid rgba(255,255,255,0.28)",
              background: "rgba(255,255,255,0.14)", display: "inline-flex", alignItems: "center",
              justifyContent: "center", cursor: "pointer", backdropFilter: "blur(4px)",
            }}>
              <Icon name="shield_keyhole" size={20} filled color="#fff" />
            </button>
          </div>
        </div>

        <div style={{ position: "relative", display: "flex", alignItems: "center", gap: 12, marginTop: 16 }}>
          <span style={{
            display: "inline-flex", alignItems: "center", gap: 6, padding: "6px 12px",
            borderRadius: 999, background: "rgba(0,0,0,0.18)", fontSize: 13, fontWeight: 600,
          }}>
            <Icon name="calendar_ltr" size={15} color="rgba(255,255,255,0.85)" />
            {T.meta.dates}
          </span>
          <AvatarStack people={T.people} size={28} />
        </div>

        {/* countdown ribbon */}
        <div style={{
          position: "relative", marginTop: 20, display: "flex", alignItems: "center",
          justifyContent: "space-between", padding: "12px 16px", borderRadius: 14,
          background: "rgba(255,255,255,0.14)", border: "1px solid rgba(255,255,255,0.2)",
        }}>
          <div>
            <div style={{ fontSize: 12, color: "rgba(255,255,255,0.75)", fontWeight: 600 }}>
              {onTrip ? "On the ground" : isDepartDay ? "Tonight" : afterTrip ? "That's a wrap" : "Wheels up"}
            </div>
            <div style={{ fontSize: 19, fontWeight: 700, marginTop: 1 }}>
              {onTrip ? `${todayDayStr} · Hanoi`
                : isDepartDay ? "Fly out tonight — Hanoi by 6 AM"
                : afterTrip ? "Hẹn gặp lại, Việt Nam!"
                : daysToGo > 0 ? `${(T.cities[0] && T.cities[0].name) || "Vietnam"} awaits — ${countdownLabel}`
                : "Enjoy the trip!"}
            </div>
          </div>
          <Icon name={afterTrip ? "heart" : "airplane_take_off"} size={26} color="rgba(255,255,255,0.9)" />
        </div>
      </div>

      {/* ---------- BODY ---------- */}
      <div style={{ padding: "16px 16px 8px", display: "flex", flexDirection: "column", gap: 14 }}>
        {/* today's plan — shown only while the trip is happening */}
        {onTrip && <TodayCard dayStr={todayDayStr} dayNum={todayIdx + 1} total={tripDays.length} places={todayPlaces} go={go} />}

        {/* flights */}
        {T.meta.flights && <FlightCard flights={T.meta.flights} />}

        {/* progress */}
        <Card pad={16}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
            <Overline>Trip progress</Overline>
            <span style={{ fontSize: 12.5, color: "var(--colorNeutralForeground3)", fontWeight: 600 }}>{visited} of {totalPlaces} places</span>
          </div>
          <Progress value={visited} max={totalPlaces} />
          <div style={{ display: "flex", gap: 8, marginTop: 12 }}>
            <StatTile label="Places seen" value={`${visited}`} sub={`of ${totalPlaces}`} icon="location" color="var(--color-teal)" onClick={() => go("places")} />
            <StatTile label="Spent" value={T.fmtVND(spent)} sub={T.toINR(spent)} icon="wallet" color="var(--color-pumpkin)" onClick={() => go("money")} />
            <StatTile label="Photos" value={`${photos}`} sub="memories" icon="image_multiple" color="var(--color-grape)" onClick={() => go("photos")} />
          </div>
        </Card>

        {/* quick actions */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {actions.map((a) => (
            <button key={a.label} onClick={a.onClick} style={{
              display: "flex", alignItems: "center", gap: 11, padding: "13px 14px",
              borderRadius: 16, border: "1px solid var(--colorNeutralStroke2)",
              background: "var(--colorNeutralBackground1)", cursor: "pointer",
              boxShadow: "var(--shadow2)", textAlign: "left", fontFamily: "var(--fontFamilyBase)",
            }}>
              <span style={{ width: 38, height: 38, borderRadius: 11, background: a.tone,
                display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                <Icon name={a.icon} size={20} filled color={a.label === "Add photo" ? "#fff" : "#fff"} />
              </span>
              <span style={{ fontSize: 14, fontWeight: 600, color: "var(--colorNeutralForeground1)" }}>{a.label}</span>
            </button>
          ))}
        </div>

        {/* route */}
        <div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "4px 2px 10px" }}>
            <Overline>Your route</Overline>
            <button onClick={() => go("places")} style={{ border: "none", background: "none", color: "var(--color-darkTeal)", fontWeight: 600, fontSize: 13, cursor: "pointer" }}>See all places</button>
          </div>
          <div style={{ display: "flex", gap: 12, overflowX: "auto", paddingBottom: 6, margin: "0 -16px", padding: "0 16px 6px" }}>
            {T.cities.map((c, i) => {
              const cityPlaces = state.places.filter((p) => p.city === c.id);
              const seen = cityPlaces.filter((p) => p.visited).length;
              return (
                <div key={c.id} style={{ flex: "0 0 auto", width: 156 }}>
                  <Card pad={0} interactive onClick={() => go("places")} style={{ overflow: "hidden" }}>
                    <div style={{ height: 84, position: "relative",
                      background: `linear-gradient(135deg, ${cityGrad(i)[0]}, ${cityGrad(i)[1]})` }}>
                      <span style={{ position: "absolute", top: 8, left: 10, fontSize: 12, fontWeight: 700, color: "rgba(255,255,255,0.9)" }}>0{i + 1}</span>
                      <span style={{ position: "absolute", bottom: 8, right: 10 }}>
                        <Chip tone="neutral" style={{ background: "rgba(255,255,255,0.9)", color: "#222" }}>{seen}/{cityPlaces.length}</Chip>
                      </span>
                    </div>
                    <div style={{ padding: "10px 12px 12px" }}>
                      <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--colorNeutralForeground1)" }}>{c.name}</div>
                      <div style={{ fontSize: 12, color: "var(--colorNeutralForeground3)", marginTop: 1 }}>{c.days}</div>
                    </div>
                  </Card>
                </div>
              );
            })}
          </div>
        </div>

        {/* up next */}
        <Card pad={14} interactive onClick={() => go("places")}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <span style={{ width: 42, height: 42, borderRadius: 12, background: "rgba(234,163,0,0.16)", display: "inline-flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
              <Icon name="food" size={22} color="var(--color-brass)" />
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <Overline color="var(--color-brass)">Up next · food to find</Overline>
              <div style={{ fontSize: 14.5, fontWeight: 600, marginTop: 2, color: "var(--colorNeutralForeground1)" }}>Bánh chả at Hương Liên, Hanoi</div>
            </div>
            <Icon name="chevron_right" size={18} color="var(--colorNeutralForeground3)" />
          </div>
        </Card>
      </div>
    </div>
  );
}

function TodayCard({ dayStr, dayNum, total, places, go }) {
  const TIME_TONE = { Morning: "var(--color-marigold)", Afternoon: "var(--color-teal)", Evening: "var(--color-pumpkin)", Night: "var(--color-grape)" };
  const order = ["Morning", "Afternoon", "Evening", "Night"];
  const byTime = {};
  places.forEach((p) => { (byTime[p.time] = byTime[p.time] || []).push(p); });
  const groups = order.filter((t) => byTime[t]);
  // strip the "Day N · " prefix → just the date part, e.g. "Wed 24"
  const dateOnly = (dayStr || "").split("·").pop().trim();
  return (
    <Card pad={16}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 11, fontWeight: 800, letterSpacing: "0.04em", color: "#fff", background: "var(--color-teal)", padding: "3px 9px", borderRadius: 999 }}>TODAY</span>
          <div>
            <div style={{ fontSize: 14.5, fontWeight: 700, color: "var(--colorNeutralForeground1)" }}>Day {dayNum} of {total}{dateOnly ? ` · ${dateOnly}` : ""}</div>
            <div style={{ fontSize: 11.5, color: "var(--colorNeutralForeground3)" }}>Hanoi · your plan for today</div>
          </div>
        </div>
        <button onClick={() => go("places")} style={{ border: "none", background: "none", color: "var(--color-darkTeal)", fontWeight: 600, fontSize: 12.5, cursor: "pointer" }}>Itinerary →</button>
      </div>
      {places.length === 0 ? (
        <div style={{ fontSize: 13.5, color: "var(--colorNeutralForeground3)", padding: "4px 0" }}>Free day — wander, eat, and see where Hanoi takes you. ✨</div>
      ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {groups.map((t) => (
            <div key={t}>
              <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 6 }}>
                <span style={{ width: 7, height: 7, borderRadius: "50%", background: TIME_TONE[t] }} />
                <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--colorNeutralForeground3)" }}>{t}</span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 2, paddingLeft: 14 }}>
                {byTime[t].map((p) => (
                  <button key={p.id} onClick={() => go("places")} style={{ display: "flex", alignItems: "center", gap: 9, padding: "5px 0", border: "none", background: "none", cursor: "pointer", textAlign: "left", fontFamily: "var(--fontFamilyBase)", width: "100%" }}>
                    <Icon name={p.visited ? "checkmark_circle" : "location"} size={16} filled={p.visited} color={p.visited ? "var(--color-green)" : "var(--colorNeutralForeground4)"} />
                    <span style={{ flex: 1, fontSize: 14, fontWeight: 600, color: "var(--colorNeutralForeground1)", textDecoration: p.visited ? "line-through" : "none", opacity: p.visited ? 0.6 : 1 }}>{p.name}</span>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}

function FlightCard({ flights }) {
  const legs = [flights.outbound, flights.ret].filter(Boolean);
  return (
    <Card pad={16}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
          <Icon name="airplane_take_off" size={16} color="var(--color-teal)" filled />
          <Overline>Flights</Overline>
        </div>
        {flights.pnr && (
          <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--color-darkTeal)", background: "rgba(3,131,135,0.10)", padding: "3px 9px", borderRadius: 999 }}>Ref {flights.pnr}</span>
        )}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        {legs.map((leg, i) => (
          <div key={i}>
            {i > 0 && <div style={{ height: 1, background: "var(--colorNeutralStroke3)", margin: "0 -16px 14px" }} />}
            <FlightLeg leg={leg} />
          </div>
        ))}
      </div>
      {flights.baggage && (
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 13, paddingTop: 11, borderTop: "1px solid var(--colorNeutralStroke3)", fontSize: 11.5, color: "var(--colorNeutralForeground3)" }}>
          <span style={{ fontSize: 13 }}>🧳</span>
          {flights.baggage}
        </div>
      )}
    </Card>
  );
}

function FlightLeg({ leg }) {
  const dash = "—";
  const endpoint = (code, city, time, date, zone, align) => (
    <div style={{ flex: "0 0 auto", textAlign: align, minWidth: 88 }}>
      <div style={{ fontSize: 22, fontWeight: 800, color: "var(--colorNeutralForeground1)", letterSpacing: "-0.01em", lineHeight: 1 }}>{code || dash}</div>
      <div style={{ fontSize: 11, color: "var(--colorNeutralForeground3)", marginTop: 2 }}>{city}</div>
      <div style={{ fontSize: 15, fontWeight: 700, color: "var(--color-darkTeal)", marginTop: 6 }}>{time || dash}</div>
      <div style={{ fontSize: 11, color: "var(--colorNeutralForeground3)", marginTop: 1 }}>{[date, zone].filter(Boolean).join(" · ") || "to be added"}</div>
    </div>
  );
  const meta = [leg.stops, leg.duration, leg.cls].filter(Boolean).join(" · ");
  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 8 }}>
        <Overline color="var(--color-teal)">{leg.label}</Overline>
        {(leg.airline || leg.flightNo) && (
          <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--colorNeutralForeground3)" }}>{[leg.airline, leg.flightNo].filter(Boolean).join(" · ")}</span>
        )}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {endpoint(leg.fromCode, leg.fromCity, leg.departTime, leg.departDate, leg.departZone, "left")}
        <div style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", color: "var(--colorNeutralForeground4)" }}>
          <div style={{ display: "flex", alignItems: "center", width: "100%" }}>
            <div style={{ flex: 1, height: 1, background: "var(--colorNeutralStroke2)" }} />
            <Icon name="airplane_take_off" size={16} color="var(--color-teal)" filled />
            <div style={{ flex: 1, height: 1, background: "var(--colorNeutralStroke2)" }} />
          </div>
          {meta && <div style={{ fontSize: 10, color: "var(--colorNeutralForeground3)", marginTop: 4, whiteSpace: "nowrap" }}>{meta}</div>}
        </div>
        {endpoint(leg.toCode, leg.toCity, leg.arriveTime, leg.arriveDate, leg.arriveZone, "right")}
      </div>
      {leg.seats && (
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 9, fontSize: 11.5, color: "var(--colorNeutralForeground3)" }}>
          <span style={{ fontSize: 13 }}>💺</span>
          Seats <b style={{ color: "var(--colorNeutralForeground2)" }}>{leg.seats}</b>
        </div>
      )}
      {leg.leaveHome && (
        <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 9, fontSize: 11.5, color: "var(--colorNeutralForeground3)" }}>
          <Icon name="home" size={13} color="var(--colorNeutralForeground3)" />
          Leave home by <b style={{ color: "var(--colorNeutralForeground2)" }}>{leg.leaveHome}</b>
        </div>
      )}
    </div>
  );
}

function StatTile({ label, value, sub, icon, color, onClick }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, textAlign: "left", border: "none", background: "var(--colorNeutralBackground2)",
      borderRadius: 13, padding: "11px 11px 12px", cursor: "pointer", fontFamily: "var(--fontFamilyBase)",
    }}>
      <Icon name={icon} size={17} filled color={color} />
      <div style={{ fontSize: 19, fontWeight: 700, marginTop: 6, color: "var(--colorNeutralForeground1)", letterSpacing: "-0.01em" }}>{value}</div>
      <div style={{ fontSize: 11, color: "var(--colorNeutralForeground3)", fontWeight: 600 }}>{label}</div>
    </button>
  );
}

function cityGrad(i) {
  const grads = [
    ["#0a7075", "#038387"],
    ["#0e7c84", "#13a8a0"],
    ["#8a5a14", "#ca5010"],
    ["#b97400", "#eaa300"],
    ["#5c2e91", "#7160e8"],
  ];
  return grads[i % grads.length];
}

Object.assign(window, { HomeScreen });
