// Home / Dashboard screen

function HomeScreen({ theme, accent, onNav, onAskHimma, onOpenPaywall }) {
  const [nwPeriod, setNwPeriod] = React.useState("year"); // 'week' | 'month' | 'year'
  const [allocationView, setAllocationView] = React.useState("assets"); // 'assets' | 'liabilities'
  const total = NET_WORTH;
  const period = NW_PERIODS[nwPeriod];

  const allocationData =
    allocationView === "assets" ? ASSET_BREAKDOWN : LIABILITY_BREAKDOWN;
  const allocationTotal =
    allocationView === "assets" ? ASSETS_TOTAL : LIABILITIES_TOTAL;

  return (
    <Screen theme={theme} padTop={0}>
      <AppTopbar
        theme={theme}
        accent={accent}
        onNav={onNav}
        onAskHimma={onAskHimma}
      />

      {/* Net worth hero card */}
      <div>
        <Card
          theme={theme}
          padded={false}
          style={{
            padding: 22,
            background: "transparent",
            border: "none",
            borderRadius: 0,
            position: "relative",
            overflow: "hidden",
          }}
        >
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "flex-start",
            }}
          >
            <SectionLabel theme={theme}>Total Net Worth</SectionLabel>
            <PeriodToggle
              value={nwPeriod}
              onChange={setNwPeriod}
              theme={theme}
              accent={accent}
            />
          </div>

          <div style={{ marginTop: 8 }}>
            <BigNumber value={total} theme={theme} accent={accent} size={42} />
          </div>

          {/* Assets / liabilities sub-legend */}
          <button
            onClick={() => onNav("assets")}
            style={{
              background: "transparent",
              border: "none",
              padding: 0,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: 10,
              marginTop: 6,
              fontFamily: FONTS.mono,
              fontSize: 10.5,
              letterSpacing: 0.2,
            }}
          >
            <span style={{ color: theme.textDim }}>
              <span style={{ color: theme.positive }}>+</span>{" "}
              {fmtAED(ASSETS_TOTAL, { compact: true })}{" "}
              <span style={{ color: theme.textMute }}>assets</span>
            </span>
            <span style={{ color: theme.textMute }}>·</span>
            <span style={{ color: theme.textDim }}>
              <span style={{ color: theme.negative }}>−</span>{" "}
              {fmtAED(LIABILITIES_TOTAL, { compact: true })}{" "}
              <span style={{ color: theme.textMute }}>debts</span>
            </span>
          </button>

          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 10,
              marginTop: 10,
            }}
          >
            <Delta
              value={period.delta}
              pct={period.pct}
              theme={theme}
              size={13}
            />
            <span style={{ fontSize: 12, color: theme.textDim }}>
              +{fmtAED(period.delta)} {period.caption}
            </span>
          </div>

          {/* Mini trend */}
          <div style={{ marginTop: 18 }}>
            <Spark
              data={period.trend}
              width={260}
              height={38}
              color={accent}
              responsive
            />
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                fontFamily: FONTS.mono,
                fontSize: 9,
                color: theme.textMute,
                marginTop: 4,
                letterSpacing: 0.5,
              }}
            >
              <span>{period.axis[0]}</span>
              <span>{period.axis[1]}</span>
            </div>
          </div>
        </Card>
      </div>

      {/* AI insight strip */}
      <div style={{ padding: "14px 16px 0" }}>
        <button
          onClick={onAskHimma}
          style={{
            width: "100%",
            textAlign: "left",
            background: "transparent",
            border: `0.5px solid ${theme.line2}`,
            borderRadius: 16,
            padding: "14px 16px",
            display: "flex",
            gap: 12,
            alignItems: "flex-start",
            cursor: "pointer",
            color: theme.text,
          }}
        >
          <div
            style={{
              width: 28,
              height: 28,
              borderRadius: 14,
              flexShrink: 0,
              background: `${accent}18`,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              color: accent,
            }}
          >
            <Ico.sparkles size={14} />
          </div>
          <div style={{ flex: 1 }}>
            <div
              style={{
                fontFamily: FONTS.mono,
                fontSize: 9.5,
                letterSpacing: 1.4,
                textTransform: "uppercase",
                color: accent,
                marginBottom: 3,
              }}
            >
              Himma · Morning note
            </div>
            <div
              style={{
                fontSize: 13.5,
                lineHeight: 1.45,
                color: theme.text,
                fontFamily: FONTS.ui,
              }}
            >
              Portfolio up <b>4.2%</b> this month — Saxo world-index drove{" "}
              <b>
                <Dh /> 18.4K
              </b>{" "}
              of gains. Your idle cash is also creeping up.
            </div>
          </div>
          <Ico.chevR
            size={15}
            style={{ color: theme.textMute, marginTop: 3 }}
          />
        </button>
      </div>

      {/* Allocation breakdown — toggle between assets and liabilities */}
      <div style={{ padding: "22px 16px 0" }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "0 4px 10px",
          }}
        >
          <SectionLabel theme={theme}>Allocation</SectionLabel>
          <button
            onClick={() => onNav("assets")}
            style={{
              background: "transparent",
              border: "none",
              fontFamily: FONTS.ui,
              fontSize: 12,
              color: theme.textDim,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: 3,
            }}
          >
            Details <Ico.chevR size={12} />
          </button>
        </div>
        <Card theme={theme} padded={false} style={{ padding: 20 }}>
          <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
            {[
              { key: "assets", label: "Assets" },
              { key: "liabilities", label: "Liabilities" },
            ].map((opt) => {
              const active = allocationView === opt.key;
              return (
                <button
                  key={opt.key}
                  onClick={() => setAllocationView(opt.key)}
                  style={{
                    flex: 1,
                    background: active ? `${accent}18` : "transparent",
                    color: active ? accent : theme.textMute,
                    border: `0.5px solid ${active ? accent + "55" : theme.line2}`,
                    borderRadius: 999,
                    padding: "6px 10px",
                    fontFamily: FONTS.ui,
                    fontSize: 12,
                    fontWeight: active ? 600 : 500,
                    cursor: "pointer",
                  }}
                >
                  {opt.label}
                </button>
              );
            })}
          </div>
          <div style={{ display: "flex", gap: 18, alignItems: "center" }}>
            <Donut
              segments={allocationData}
              size={120}
              stroke={13}
              theme={theme}
              centerValue={
                <span
                  style={{
                    display: "inline-flex",
                    alignItems: "baseline",
                    gap: 3,
                  }}
                >
                  <Dh size={11} color={theme.text} />
                  {fmtAED(allocationTotal, { compact: true })}
                </span>
              }
            />
            <div
              style={{
                flex: 1,
                display: "flex",
                flexDirection: "column",
                gap: 9,
              }}
            >
              {allocationData.map((s) => {
                const pct = (s.value / allocationTotal) * 100;
                return (
                  <div
                    key={s.key}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 9,
                      fontSize: 12,
                    }}
                  >
                    <div
                      style={{
                        width: 8,
                        height: 8,
                        borderRadius: 2,
                        background: s.color,
                        flexShrink: 0,
                      }}
                    />
                    <div
                      style={{
                        flex: 1,
                        color: theme.textDim,
                        fontFamily: FONTS.ui,
                      }}
                    >
                      {s.label}
                    </div>
                    <div
                      style={{
                        fontFamily: FONTS.mono,
                        color: theme.text,
                        fontVariantNumeric: "tabular-nums",
                      }}
                    >
                      {pct.toFixed(0)}%
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </Card>
      </div>

      {/* Peer comparison hook */}
      <div style={{ padding: "14px 16px 0" }}>
        <PeerCompareHook
          theme={theme}
          accent={accent}
          hideValue={false}
          onOpen={() =>
            SUBSCRIPTION.status === "active"
              ? onNav("compare")
              : onOpenPaywall && onOpenPaywall()
          }
        />
      </div>

      {/* Learn — personalized financial literacy hook tiles */}
      <div style={{ padding: "26px 16px 0" }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "0 20px 10px",
          }}
        >
          <SectionLabel theme={theme}>Learn</SectionLabel>
          <button
            onClick={() => onNav("learn")}
            style={{
              background: "transparent",
              border: "none",
              fontFamily: FONTS.ui,
              fontSize: 12,
              color: theme.textDim,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              gap: 3,
            }}
          >
            See all <Ico.chevR size={12} />
          </button>
        </div>
        <div
          style={{
            display: "flex",
            gap: 10,
            paddingLeft: 20,
            paddingRight: 16,
            paddingTop: 2,
            paddingBottom: 4,
            overflowX: "auto",
            scrollSnapType: "x mandatory",
          }}
        >
          {getRelevantLearnArticles(5).map((a) => (
            <LearnTile
              key={a.id}
              article={a}
              theme={theme}
              accent={accent}
              onClick={() => onNav("learn_article", { articleId: a.id })}
            />
          ))}
        </div>
      </div>

      {/* Footer wordmark */}
      <div
        style={{ textAlign: "center", padding: "30px 0 10px", opacity: 0.35 }}
      >
        <Wordmark color={theme.text} accent={accent} size={14} />
      </div>
    </Screen>
  );
}

const LEARN_CATEGORY_COLORS = {
  Saving: "#1F8A4C",
  Investing: "#2C5BFF",
  Property: "#C77A00",
  Crypto: "#7B5BFF",
  Tax: "#D23B2E",
  Protection: "#B8824A",
};

function LearnTile({ article, theme, onClick }) {
  const tagColor = LEARN_CATEGORY_COLORS[article.category] || theme.textDim;
  return (
    <button
      onClick={onClick}
      style={{
        flex: "0 0 auto",
        width: 158,
        scrollSnapAlign: "start",
        background: `linear-gradient(155deg, ${theme.surface2} 0%, ${theme.surface} 90%)`,
        border: `0.5px solid ${theme.line}`,
        borderRadius: 16,
        padding: 14,
        display: "flex",
        flexDirection: "column",
        gap: 10,
        textAlign: "left",
        cursor: "pointer",
        color: theme.text,
      }}
    >
      <span
        style={{
          display: "inline-flex",
          alignSelf: "flex-start",
          alignItems: "center",
          fontFamily: FONTS.mono,
          fontSize: 8.5,
          letterSpacing: 1,
          textTransform: "uppercase",
          color: tagColor,
          background: `${tagColor}18`,
          padding: "2px 6px",
          borderRadius: 4,
        }}
      >
        {article.category}
      </span>
      <div
        style={{
          fontFamily: FONTS.display,
          fontSize: 14.5,
          lineHeight: 1.25,
          color: theme.text,
          letterSpacing: -0.2,
          minHeight: 54,
        }}
      >
        {article.title}
      </div>
    </button>
  );
}

// Compact 3-segment toggle for the net-worth period (W / M / Y).
function PeriodToggle({ value, onChange, theme, accent }) {
  const opts = [
    { key: "week", label: "W" },
    { key: "month", label: "M" },
    { key: "year", label: "Y" },
  ];
  return (
    <div
      style={{
        display: "inline-flex",
        border: `0.5px solid ${theme.line2}`,
        borderRadius: 999,
        padding: 2,
        background: theme.surface,
      }}
    >
      {opts.map((o) => {
        const active = value === o.key;
        return (
          <button
            key={o.key}
            onClick={() => onChange(o.key)}
            style={{
              background: active ? `${accent}18` : "transparent",
              color: active ? accent : theme.textMute,
              border: "none",
              cursor: "pointer",
              fontFamily: FONTS.mono,
              fontSize: 10,
              letterSpacing: 1,
              fontWeight: active ? 600 : 500,
              padding: "3px 9px",
              borderRadius: 999,
              transition: "all 120ms",
            }}
          >
            {o.label}
          </button>
        );
      })}
    </div>
  );
}

// Home hook tile → curated insight surface.
function CashFlowHook({ theme, accent, hideValue }) {
  const inTotal = CASH_FLOW.in.reduce((s, x) => s + x.value, 0);
  const outOnly = CASH_FLOW.out
    .filter((o) => o.key !== "saved")
    .reduce((s, x) => s + x.value, 0);
  const saved = CASH_FLOW.out.find((o) => o.key === "saved")?.value || 0;
  const netPct = (saved / inTotal) * 100;

  const H = 6;
  const outPct = (outOnly / inTotal) * 100;

  return (
    <div
      style={{
        width: "100%",
        textAlign: "left",
        background: theme.surface,
        border: `0.5px solid ${theme.line2}`,
        borderRadius: 20,
        padding: "16px 18px",
        color: theme.text,
      }}
    >
      <SectionLabel theme={theme}>Insight</SectionLabel>

      <div
        style={{
          marginTop: 10,
          fontFamily: FONTS.display,
          fontSize: 20,
          lineHeight: 1.2,
          letterSpacing: -0.4,
        }}
      >
        {hideValue ? (
          <>
            You saved <span style={{ color: theme.textMute }}>•••</span> of
            income last month
          </>
        ) : (
          <>
            You saved{" "}
            <span style={{ color: accent }}>{netPct.toFixed(0)}%</span> of
            income last month
          </>
        )}
      </div>

      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: 10,
          marginTop: 14,
        }}
      >
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 2,
            flexShrink: 0,
          }}
        >
          <span
            style={{
              fontFamily: FONTS.mono,
              fontSize: 9,
              letterSpacing: 1,
              textTransform: "uppercase",
              color: theme.textMute,
            }}
          >
            In
          </span>
          <span
            style={{
              fontFamily: FONTS.mono,
              fontSize: 12,
              color: theme.positive,
              fontVariantNumeric: "tabular-nums",
            }}
          >
            {hideValue ? "•••" : `+${fmtAED(inTotal, { compact: true })}`}
          </span>
        </div>
        <div
          style={{
            flex: 1,
            position: "relative",
            height: H,
            borderRadius: H / 2,
            background: theme.surface3,
            overflow: "hidden",
          }}
        >
          <div
            style={{
              position: "absolute",
              left: 0,
              top: 0,
              bottom: 0,
              width: `${outPct}%`,
              background: theme.textDim,
              opacity: 0.55,
            }}
          />
          <div
            style={{
              position: "absolute",
              left: `${outPct}%`,
              top: 0,
              bottom: 0,
              right: 0,
              background: accent,
            }}
          />
        </div>
        <div
          style={{
            display: "flex",
            flexDirection: "column",
            gap: 2,
            flexShrink: 0,
            textAlign: "right",
          }}
        >
          <span
            style={{
              fontFamily: FONTS.mono,
              fontSize: 9,
              letterSpacing: 1,
              textTransform: "uppercase",
              color: theme.textMute,
            }}
          >
            Out
          </span>
          <span
            style={{
              fontFamily: FONTS.mono,
              fontSize: 12,
              color: theme.text,
              fontVariantNumeric: "tabular-nums",
            }}
          >
            {hideValue ? "•••" : `−${fmtAED(outOnly, { compact: true })}`}
          </span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, CashFlowHook, PeriodToggle });
