// Compare — peer comparison screen + Home hook tile

// Returns a label like "Last 3 full months · Jan – Mar" relative to today.
function getFullMonthsLabel(n) {
  const NAMES = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];
  const today = new Date();
  // Last full month = previous calendar month from today.
  const endIdx = (today.getMonth() - 1 + 12) % 12;
  const startIdx = (endIdx - (n - 1) + 12) % 12;
  return `Last ${n} full months · ${NAMES[startIdx]} – ${NAMES[endIdx]}`;
}

// Returns just the month range, e.g. "Jan – Mar".
function getRangeLabel(n) {
  const NAMES = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec",
  ];
  const today = new Date();
  const endIdx = (today.getMonth() - 1 + 12) % 12;
  const startIdx = (endIdx - (n - 1) + 12) % 12;
  return `${NAMES[startIdx]} – ${NAMES[endIdx]}`;
}

// ── Shared sub-component: percentile distribution bar ──────────────────────
function PercentileBar({
  percentile,
  theme,
  accent,
  height = 10,
  showTicks = true,
  medianLabel,
  tickLabels,
}) {
  // Quartile tick positions on a 0–100 axis.
  const ticks = [25, 50, 75, 90];
  const dotPos = Math.max(2, Math.min(98, percentile));
  return (
    <div style={{ width: "100%", position: "relative" }}>
      <div
        style={{
          position: "relative",
          width: "100%",
          height,
          background: theme.surface2,
          borderRadius: height / 2,
          overflow: "visible",
        }}
      >
        {/* Filled portion up to user's percentile */}
        <div
          style={{
            position: "absolute",
            top: 0,
            bottom: 0,
            left: 0,
            width: `${dotPos}%`,
            background: `linear-gradient(90deg, ${accent}40, ${accent})`,
            borderRadius: height / 2,
          }}
        />
        {/* Quartile ticks */}
        {showTicks &&
          ticks.map((t) => (
            <div
              key={t}
              style={{
                position: "absolute",
                top: -2,
                bottom: -2,
                left: `${t}%`,
                width: 1,
                background: theme.line2,
                opacity: 0.7,
              }}
            />
          ))}
        {/* Median label sitting on the median tick */}
        {medianLabel && (
          <div
            style={{
              position: "absolute",
              left: "50%",
              top: -28,
              transform: "translateX(-50%)",
              fontFamily: FONTS.mono,
              fontSize: 9.5,
              letterSpacing: 0.4,
              color: theme.textDim,
              whiteSpace: "nowrap",
              background: theme.bg,
              padding: "2px 6px",
              borderRadius: 4,
              border: `0.5px solid ${theme.line2}`,
            }}
          >
            {medianLabel}
          </div>
        )}
        {/* "You" dot */}
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: `${dotPos}%`,
            width: 14,
            height: 14,
            borderRadius: 7,
            background: accent,
            border: `2px solid ${theme.bg}`,
            transform: "translate(-50%, -50%)",
            boxShadow: `0 0 0 1px ${accent}`,
          }}
        />
      </div>
      {/* Tick labels positioned exactly under each tick */}
      {tickLabels && (
        <div style={{ position: "relative", height: 14, marginTop: 7 }}>
          {ticks.map((t, i) => (
            <span
              key={t}
              style={{
                position: "absolute",
                left: `${t}%`,
                transform: "translateX(-50%)",
                fontFamily: FONTS.mono,
                fontSize: 9,
                color: theme.textMute,
                letterSpacing: 0.5,
                textTransform: "uppercase",
                whiteSpace: "nowrap",
              }}
            >
              {tickLabels[i]}
            </span>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Home hook tile ─────────────────────────────────────────────────────────
function PeerCompareHook({ theme, accent, hideValue, onOpen }) {
  const data = getPeerComparison();
  // "Better off than" = the user's percentile (she's above that many peers).
  // "Behind" = 100 - percentile (peers ahead of her).
  const peersBelow = data.percentile;
  const peersAbove = 100 - data.percentile;
  const ahead = data.percentile >= 50;

  return (
    <button
      onClick={onOpen}
      style={{
        width: "100%",
        textAlign: "left",
        background: theme.surface,
        border: `0.5px solid ${theme.line2}`,
        borderRadius: 20,
        padding: "18px 18px 16px",
        cursor: "pointer",
        color: theme.text,
        display: "block",
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 10,
        }}
      >
        <SectionLabel theme={theme}>How you compare</SectionLabel>
        <div
          style={{
            display: "flex",
            alignItems: "center",
            gap: 4,
            fontFamily: FONTS.mono,
            fontSize: 9.5,
            letterSpacing: 1,
            color: theme.textDim,
            textTransform: "uppercase",
            whiteSpace: "nowrap",
          }}
        >
          {COHORT_LABELS[`gender:${USER.gender}`]} · {USER.ageBracket} ·{" "}
          {COHORT_LABELS[`city:${USER.city}`]}
          <Ico.chevR size={11} />
        </div>
      </div>

      <div
        style={{
          marginTop: 10,
          fontFamily: FONTS.display,
          fontSize: 22,
          lineHeight: 1.2,
          letterSpacing: -0.4,
        }}
      >
        {hideValue ? (
          <>
            You're <span style={{ color: theme.textMute }}>•••</span> peers in
            net worth
          </>
        ) : ahead ? (
          <>
            Better off than{" "}
            <span style={{ color: accent }}>{peersBelow} of 100</span> peers in
            net worth
          </>
        ) : (
          <>
            You're below{" "}
            <span style={{ color: accent }}>{peersAbove} of 100</span> peers in
            net worth
          </>
        )}
      </div>

      <div style={{ marginTop: 14 }}>
        <PercentileBar
          percentile={hideValue ? 50 : data.percentile}
          theme={theme}
          accent={accent}
          height={8}
        />
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            fontFamily: FONTS.mono,
            fontSize: 9,
            color: theme.textMute,
            letterSpacing: 0.5,
            marginTop: 6,
            textTransform: "uppercase",
          }}
        >
          <span>Bottom</span>
          <span>Median</span>
          <span>Top</span>
        </div>
      </div>
    </button>
  );
}

// ── Cohort customizer (modal sheet) ────────────────────────────────────────
function CohortCustomizer({ theme, accent, filters, onApply, onClose }) {
  const [draft, setDraft] = React.useState(filters);
  const preview = getPeerComparison(draft);
  const sample = preview.tooSmall ? preview.sample : preview.sample;

  const FilterSection = ({ k, title, options }) => (
    <div style={{ padding: "14px 16px 6px" }}>
      <SectionLabel theme={theme} style={{ marginBottom: 8 }}>
        {title}
      </SectionLabel>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
        {options.map((o) => {
          const active = draft[k] === o.id;
          return (
            <button
              key={o.id}
              onClick={() => setDraft((d) => ({ ...d, [k]: o.id }))}
              style={{
                background: active ? theme.text : "transparent",
                color: active ? theme.bg : theme.text,
                border: `0.5px solid ${active ? theme.text : theme.line2}`,
                borderRadius: 999,
                padding: "8px 13px",
                fontSize: 12.5,
                fontFamily: FONTS.ui,
                fontWeight: 500,
                cursor: "pointer",
                whiteSpace: "nowrap",
              }}
            >
              {dhText(o.label)}
            </button>
          );
        })}
      </div>
    </div>
  );

  return (
    <div
      style={{
        position: "absolute",
        inset: 0,
        zIndex: 80,
        background: "rgba(10,10,10,0.4)",
        display: "flex",
        alignItems: "flex-end",
      }}
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          width: "100%",
          background: theme.bg,
          borderTopLeftRadius: 24,
          borderTopRightRadius: 24,
          paddingBottom: 28,
          maxHeight: "85%",
          overflowY: "auto",
        }}
      >
        {/* Drag handle */}
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            padding: "10px 0 4px",
          }}
        >
          <div
            style={{
              width: 36,
              height: 4,
              borderRadius: 2,
              background: theme.line2,
            }}
          />
        </div>

        {/* Header */}
        <div
          style={{
            padding: "8px 18px 4px",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <div
            style={{ fontFamily: FONTS.display, fontSize: 18, fontWeight: 500 }}
          >
            Customize cohort
          </div>
          <button
            onClick={onClose}
            style={{
              width: 32,
              height: 32,
              borderRadius: 16,
              background: theme.surface2,
              border: "none",
              color: theme.text,
              cursor: "pointer",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Ico.close size={14} />
          </button>
        </div>
        <div
          style={{
            padding: "0 18px 8px",
            fontSize: 12.5,
            color: theme.textDim,
            lineHeight: 1.4,
          }}
        >
          Pick the group you want to compare yourself to. Cohorts under 200
          peers are hidden for privacy.
        </div>

        <FilterSection k="age" title="Age range" options={COHORT_OPTIONS.age} />

        {/* Fallback notice (shown only when there's no exact cohort match) */}
        {!preview.tooSmall && preview.isFallback && (
          <div style={{ padding: "14px 16px 0" }}>
            <div
              style={{
                background: theme.surface2,
                borderRadius: 14,
                padding: "12px 14px",
                fontSize: 11.5,
                color: theme.textDim,
                lineHeight: 1.4,
              }}
            >
              Showing the closest matching cohort.
            </div>
          </div>
        )}
        {preview.tooSmall && (
          <div style={{ padding: "14px 16px 0" }}>
            <div
              style={{
                background: theme.surface2,
                borderRadius: 14,
                padding: "12px 14px",
                fontSize: 11.5,
                color: theme.textDim,
                lineHeight: 1.4,
              }}
            >
              Cohort too small. Broaden filters to see results.
            </div>
          </div>
        )}

        {/* Apply */}
        <div style={{ padding: "16px 16px 0" }}>
          <button
            onClick={() => onApply(draft)}
            disabled={preview.tooSmall}
            style={{
              width: "100%",
              background: preview.tooSmall ? theme.surface2 : theme.text,
              color: preview.tooSmall ? theme.textMute : theme.bg,
              border: "none",
              padding: "14px",
              borderRadius: 14,
              fontFamily: FONTS.ui,
              fontSize: 14,
              fontWeight: 500,
              cursor: preview.tooSmall ? "not-allowed" : "pointer",
            }}
          >
            Show comparison
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Compare screen ─────────────────────────────────────────────────────────
function CompareScreen({ theme, accent, onBack }) {
  const [filters, setFilters] = React.useState({
    age: USER.ageBracket,
    gender: USER.gender,
    city: USER.city,
    income: USER.incomeTier,
  });
  const [showCustomizer, setShowCustomizer] = React.useState(false);

  const data = getPeerComparison(filters);

  // Defensive — should never trip with seeded data, but guards manual filter combos.
  if (data.tooSmall) {
    return (
      <Screen theme={theme} padTop={0}>
        <NavBar theme={theme} title="Compare" onBack={onBack} />
        <div style={{ padding: "40px 24px", textAlign: "center" }}>
          <div
            style={{ fontFamily: FONTS.display, fontSize: 18, marginBottom: 8 }}
          >
            Cohort too small
          </div>
          <div style={{ fontSize: 13, color: theme.textDim, marginBottom: 20 }}>
            Only {data.sample} peers match these filters. Broaden them to see a
            comparison.
          </div>
          <button
            onClick={() => setShowCustomizer(true)}
            style={{
              background: theme.text,
              color: theme.bg,
              border: "none",
              padding: "12px 18px",
              borderRadius: 12,
              fontSize: 13,
              cursor: "pointer",
            }}
          >
            Adjust cohort
          </button>
        </div>
        {showCustomizer && (
          <CohortCustomizer
            theme={theme}
            accent={accent}
            filters={filters}
            onApply={(f) => {
              setFilters(f);
              setShowCustomizer(false);
            }}
            onClose={() => setShowCustomizer(false)}
          />
        )}
      </Screen>
    );
  }

  // "Better off than" = the user's percentile (she's above that many peers).
  // "Behind" = 100 - percentile (peers ahead of her).
  const peersBelow = data.percentile;
  const peersAbove = 100 - data.percentile;
  const ahead = data.percentile >= 50;

  return (
    <Screen theme={theme} padTop={0}>
      <NavBar theme={theme} title="Compare" onBack={onBack} />

      {/* Cohort pill */}
      <div style={{ padding: "0 16px 14px" }}>
        <button
          onClick={() => setShowCustomizer(true)}
          style={{
            width: "100%",
            textAlign: "left",
            background: theme.surface2,
            border: `0.5px solid ${theme.line}`,
            borderRadius: 14,
            padding: "12px 14px",
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            gap: 10,
            cursor: "pointer",
            color: theme.text,
          }}
        >
          <div style={{ minWidth: 0 }}>
            <div
              style={{
                fontFamily: FONTS.mono,
                fontSize: 9.5,
                letterSpacing: 1.3,
                color: theme.textMute,
                textTransform: "uppercase",
                marginBottom: 3,
              }}
            >
              Comparing to
            </div>
            <div
              style={{
                fontSize: 13,
                color: theme.text,
                fontWeight: 500,
                whiteSpace: "nowrap",
                overflow: "hidden",
                textOverflow: "ellipsis",
              }}
            >
              {COHORT_LABELS[`age:${filters.age}`]}
            </div>
            {data.isFallback && (
              <div
                style={{
                  fontFamily: FONTS.mono,
                  fontSize: 10.5,
                  color: theme.textDim,
                  marginTop: 3,
                  letterSpacing: 0.3,
                }}
              >
                Closest match
              </div>
            )}
          </div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              color: accent,
              fontSize: 12,
              fontWeight: 500,
              whiteSpace: "nowrap",
            }}
          >
            Change <Ico.chevR size={13} />
          </div>
        </button>
      </div>

      {/* Net worth hero */}
      <div style={{ padding: "0 16px 18px" }}>
        <Card
          theme={theme}
          padded={false}
          style={{
            padding: 20,
            background: `linear-gradient(155deg, ${accent}08 0%, ${theme.surface} 80%)`,
          }}
        >
          <SectionLabel theme={theme}>Net worth</SectionLabel>
          <div
            style={{
              marginTop: 8,
              fontFamily: FONTS.display,
              fontSize: 22,
              lineHeight: 1.25,
              letterSpacing: -0.4,
            }}
          >
            {ahead ? (
              <>
                You're in the{" "}
                <span style={{ color: accent }}>top {peersAbove}%</span> —
                better off than <b>{peersBelow} of 100</b> peers
              </>
            ) : (
              <>
                You're in the bottom {peersBelow}% — only{" "}
                <b>{peersAbove} of 100</b> peers are below you
              </>
            )}
          </div>

          <div style={{ marginTop: 36 }}>
            <PercentileBar
              percentile={data.percentile}
              theme={theme}
              accent={accent}
              height={12}
              medianLabel={
                <>{fmtAED(data.netWorth.peerMedian, { compact: true })}</>
              }
              tickLabels={["p25", "Median", "p75", "Top 10%"]}
            />
          </div>
        </Card>
      </div>

      {/* Spending grid */}
      <div style={{ padding: "0 16px 14px" }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "0 4px 10px",
            gap: 8,
          }}
        >
          <SectionLabel theme={theme}>Avg. Spend vs. peers</SectionLabel>
          <span
            style={{
              fontFamily: FONTS.mono,
              fontSize: 9.5,
              color: theme.textMute,
              letterSpacing: 0.6,
              textTransform: "uppercase",
              whiteSpace: "nowrap",
            }}
          >
            {getRangeLabel(3)}
          </span>
        </div>

        {/* Total tile spans full width */}
        <SpendCompareTile
          data={data.spending.total}
          theme={theme}
          accent={accent}
          full
        />

        {/* Categories grid */}
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "1fr 1fr",
            gap: 10,
            marginTop: 10,
          }}
        >
          {["housing", "food", "transport", "travel"].map((k) => (
            <SpendCompareTile
              key={k}
              data={data.spending[k]}
              theme={theme}
              accent={accent}
            />
          ))}
        </div>
      </div>

      {/* Methodology */}
      <Methodology theme={theme} accent={accent} sample={data.sample} />

      <div style={{ height: 16 }} />

      {showCustomizer && (
        <CohortCustomizer
          theme={theme}
          accent={accent}
          filters={filters}
          onApply={(f) => {
            setFilters(f);
            setShowCustomizer(false);
          }}
          onClose={() => setShowCustomizer(false)}
        />
      )}
    </Screen>
  );
}

// ── Sub-components ─────────────────────────────────────────────────────────
function Stat({ theme, label, value, tone }) {
  return (
    <div>
      <div
        style={{
          fontFamily: FONTS.mono,
          fontSize: 9,
          letterSpacing: 0.8,
          color: theme.textMute,
          textTransform: "uppercase",
        }}
      >
        {label}
      </div>
      <div
        style={{
          fontFamily: FONTS.display,
          fontSize: 15,
          marginTop: 4,
          color: tone || theme.text,
          fontVariantNumeric: "tabular-nums",
        }}
      >
        {value}
      </div>
    </div>
  );
}

function SpendCompareTile({ data, theme, accent, full = false }) {
  // Spending color logic: amber (warning) for above peer median, dim for below.
  // Never red — spending more than peers isn't a moral failure.
  const tone = data.above ? theme.warning : theme.textDim;
  const sign = data.above ? "+" : "−";
  const peerPct = Math.max(8, Math.min(100, (data.peer / data.user) * 100));
  // When user spends LESS than peer, peer bar should be longer than user bar.
  const userBarPct = data.above ? 100 : (data.user / data.peer) * 100;
  const peerBarPct = data.above ? peerPct : 100;

  return (
    <Card
      theme={theme}
      padded={false}
      style={{
        padding: 14,
        background: `linear-gradient(155deg, ${accent}08 0%, ${theme.surface} 80%)`,
        ...(full ? { gridColumn: "1 / -1" } : {}),
      }}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-between",
          alignItems: "baseline",
          gap: 6,
        }}
      >
        <span
          style={{
            fontFamily: FONTS.ui,
            fontSize: 12,
            fontWeight: 700,
            color: theme.text,
            letterSpacing: -0.1,
          }}
        >
          {data.label}
        </span>
        <span
          style={{
            fontFamily: FONTS.mono,
            fontSize: 10,
            color: tone,
            fontWeight: 500,
            letterSpacing: 0.3,
            whiteSpace: "nowrap",
          }}
        >
          {sign}
          {Math.abs(data.deltaPct) >= 100
            ? `${data.ratio.toFixed(1)}×`
            : `${Math.abs(data.deltaPct).toFixed(0)}%`}
        </span>
      </div>

      {/* Side-by-side bars: you (accent) on top, peer median (muted) below */}
      <div
        style={{
          marginTop: 12,
          display: "flex",
          flexDirection: "column",
          gap: 5,
        }}
      >
        <BarRow
          theme={theme}
          label="You"
          value={data.user}
          pct={userBarPct}
          color={accent}
          bold
        />
        <BarRow
          theme={theme}
          label="Peers"
          value={data.peer}
          pct={peerBarPct}
          color={theme.textMute}
        />
      </div>
    </Card>
  );
}

function BarRow({ theme, label, value, pct, color, bold = false }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
      <div
        style={{
          width: 36,
          fontFamily: FONTS.mono,
          fontSize: 9,
          letterSpacing: 0.5,
          textTransform: "uppercase",
          color: bold ? theme.text : theme.textMute,
          fontWeight: bold ? 700 : 500,
        }}
      >
        {label}
      </div>
      <div
        style={{
          flex: 1,
          height: 6,
          background: theme.surface2,
          borderRadius: 3,
          overflow: "hidden",
        }}
      >
        <div
          style={{
            width: `${Math.max(2, Math.min(100, pct))}%`,
            height: "100%",
            background: color,
            borderRadius: 3,
          }}
        />
      </div>
      <div
        style={{
          minWidth: 56,
          textAlign: "right",
          fontFamily: FONTS.mono,
          fontSize: 10.5,
          fontVariantNumeric: "tabular-nums",
          color: bold ? theme.text : theme.textDim,
          fontWeight: bold ? 700 : 500,
        }}
      >
        {fmtAED(value, { compact: value >= 10000 })}
      </div>
    </div>
  );
}

function Methodology({ theme, accent, sample }) {
  const [open, setOpen] = React.useState(false);
  return (
    <div style={{ padding: "0 16px" }}>
      <button
        onClick={() => setOpen((o) => !o)}
        style={{
          width: "100%",
          textAlign: "left",
          background: "transparent",
          border: "none",
          cursor: "pointer",
          padding: "12px 4px",
          color: theme.textDim,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          fontFamily: FONTS.ui,
          fontSize: 12,
        }}
      >
        <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <Ico.shield size={13} /> How this is calculated
        </span>
        <Ico.chevD
          size={13}
          style={{
            transform: open ? "rotate(180deg)" : "rotate(0deg)",
            transition: "transform 150ms",
          }}
        />
      </button>
      {open && (
        <div
          style={{
            padding: "4px 4px 16px",
            fontSize: 12,
            color: theme.textDim,
            lineHeight: 1.55,
          }}
        >
          Anonymized, aggregated data from Himma Pro users in your cohort.
          Spending is averaged across the {getFullMonthsLabel(3).toLowerCase()}.
          You're never identified individually; cohorts with fewer than 200
          members are never shown. Updated monthly.
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CompareScreen, PeerCompareHook, PercentileBar });
