// Recommendations — AI insight cards

const INSIGHT_PRODUCTS = [
  {
    key: "retirement",
    route: "insights_retirement",
    label: "Life Planning",
    title: "Life Planning",
    icon: "piggy",
    tone: "#1F8A4C",
    summary:
      "Plan your independence timeline and organize the professional introductions that protect your household.",
    useCases: [
      {
        title: "FIRE tracker",
        kicker: "Independence timeline",
        body: "Track your savings rate, investable assets and target number against a clear retirement date.",
        action: "View tracker",
      },
      {
        title: "Intro to estate lawyer/professionals",
        kicker: "Will & Estate",
        body: "Connect with estate lawyers and planning specialists for wills, guardianship and asset transfer.",
        action: "Request intro",
      },
    ],
  },
  {
    key: "realestate",
    route: "insights_real_estate",
    label: "Spending",
    title: "Spending",
    icon: "wallet",
    tone: "#C97B63",
    summary:
      "Find spend leaks, rewards gaps and lending optimizations across cards, loans and cross-border activity.",
    useCases: [
      {
        title: "Credit card rewards optimization",
        kicker: "Rewards gap",
        body: "Match card usage to your highest spend categories so dining, travel and everyday purchases earn the right rewards.",
        action: "Optimize rewards",
      },
      {
        title: "Mortgage optimization",
        kicker: "Debt cost",
        body: "Review rates, fees and refinancing windows to estimate whether your mortgage can be repriced or restructured.",
        action: "Review mortgage",
      },
      {
        title: "Loan optimization",
        kicker: "Interest savings",
        body: "Compare loan balances, APRs and repayment schedules to identify consolidation or early repayment opportunities.",
        action: "Analyze loans",
      },
      {
        title: "FX spend and commissions lost",
        kicker: "Cross-border leakage",
        body: "Track foreign currency purchases, spread, card fees and brokerage commissions that quietly reduce returns.",
        action: "Find leakage",
      },
    ],
  },
  {
    key: "willestate",
    route: "insights_will_estate",
    label: "Insurance",
    title: "Insurance",
    icon: "umbrella",
    tone: "#8A6BBE",
    summary:
      "Review coverage gaps and find the policies that protect your income, home and liabilities.",
    useCases: [
      {
        title: "Existing insurance optimization",
        kicker: "Coverage review",
        body: "Review your current policies for duplicated coverage, missing riders, high deductibles and renewal savings.",
        action: "Optimize coverage",
      },
      {
        title: "Life insurance finder",
        kicker: "Family protection",
        body: "Compare term life coverage sized to your income, liabilities and dependents.",
        action: "Find life cover",
      },
      {
        title: "Disability insurance finder",
        kicker: "Income protection",
        body: "Find short- and long-term disability cover that protects your earning power if you cannot work.",
        action: "Find disability cover",
      },
      {
        title: "Legal insurance finder",
        kicker: "Legal support",
        body: "Compare legal protection plans for contract reviews, disputes and personal legal support.",
        action: "Find legal cover",
      },
      {
        title: "Homeowners insurance finder",
        kicker: "Home protection",
        body: "Compare policies for property damage, contents, liability and temporary accommodation cover.",
        action: "Find home cover",
      },
      {
        title: "Car insurance finder",
        kicker: "Vehicle protection",
        body: "Compare comprehensive and third-party policies against your vehicle value and claims history.",
        action: "Find car cover",
      },
    ],
  },
];

const INSIGHT_FILTERS = [
  { key: "all", label: "All", icon: "star", tone: "#0A0A0A" },
  {
    key: "savings",
    label: "Savings",
    icon: "piggy",
    tone: "#1F8A4C",
    categories: ["Savings"],
  },
  {
    key: "investments",
    label: "Wealth",
    icon: "lineChart",
    tone: "#D4B27A",
    categories: ["Investments"],
  },
  {
    key: "real-estate",
    label: "Spending",
    icon: "wallet",
    tone: "#C97B63",
    productKey: "realestate",
  },
  {
    key: "retirement",
    label: "Life Planning",
    icon: "target",
    tone: "#1F8A4C",
    productKey: "retirement",
  },
  {
    key: "will-estate",
    label: "Insurance",
    icon: "umbrella",
    tone: "#8A6BBE",
    productKey: "willestate",
  },
];

const INSIGHT_FILTER_PANEL_BG =
  "linear-gradient(155deg, rgb(246, 247, 249) 0%, rgb(255, 255, 255) 90%)";
const INSIGHT_FILTER_TILE_BG = "rgb(246, 247, 249)";

function isMidnightInsightsTheme(theme) {
  return theme?.label === "Midnight" && theme?.description === "slate + cyan";
}

function InsightFilterTile({ filter, active, theme, accent, onClick }) {
  const Icon = Ico[filter.icon] || Ico.star;
  const midnight = isMidnightInsightsTheme(theme);
  const iconColor = midnight ? theme.text : "rgb(10, 10, 10)";
  return (
    <button
      onClick={onClick}
      aria-pressed={active}
      style={{
        minWidth: 0,
        background: "transparent",
        border: "none",
        padding: 0,
        cursor: "pointer",
        color: theme.text,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "flex-start",
        textAlign: "center",
      }}
    >
      <div
        style={{
          width: "100%",
          maxWidth: 62,
          height: 56,
          borderRadius: 15,
          background: midnight ? theme.surface2 : INSIGHT_FILTER_TILE_BG,
          color: iconColor,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          flexShrink: 0,
          boxShadow: active ? "0 8px 18px rgba(10, 10, 10, 0.08)" : "none",
          transform: active ? "translateY(-1px)" : "none",
          transition: "box-shadow 140ms, transform 140ms",
        }}
      >
        <Icon size={24} stroke={iconColor} sw={1.5} />
      </div>
      <div
        style={{
          marginTop: 7,
          fontFamily: FONTS.ui,
          fontSize: 10.5,
          lineHeight: 1.2,
          fontWeight: active ? 600 : 400,
          color: theme.text,
          overflowWrap: "anywhere",
        }}
      >
        {filter.label}
      </div>
    </button>
  );
}

function ProductUseCaseCard({ item, theme, accent }) {
  return (
    <Card theme={theme} padded={false} style={{ padding: 16 }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12 }}>
        <div
          style={{
            width: 8,
            height: 8,
            borderRadius: 4,
            background: accent,
            marginTop: 6,
            flexShrink: 0,
          }}
        />
        <div style={{ flex: 1, minWidth: 0 }}>
          <SectionLabel theme={theme}>{item.kicker}</SectionLabel>
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 17,
              lineHeight: 1.25,
              color: theme.text,
              marginTop: 5,
              fontWeight: 600,
            }}
          >
            {item.title}
          </div>
          <div
            style={{
              marginTop: 7,
              fontFamily: FONTS.ui,
              fontSize: 13,
              lineHeight: 1.5,
              color: theme.textDim,
            }}
          >
            {item.body}
          </div>
          <button
            style={{
              background: theme.surface2,
              color: theme.text,
              border: `0.5px solid ${theme.line}`,
              borderRadius: 12,
              padding: "9px 11px",
              fontFamily: FONTS.ui,
              fontSize: 12.5,
              fontWeight: 600,
              cursor: "pointer",
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            {item.action}
            <Ico.chevR size={13} stroke={theme.textDim} />
          </button>
        </div>
      </div>
    </Card>
  );
}

function InlineInsightProduct({ product, theme, accent }) {
  return (
    <>
      {product.useCases.map((item) => (
        <Card
          key={item.title}
          theme={theme}
          padded={false}
          style={{ padding: 18 }}
        >
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 17,
              color: theme.text,
              marginTop: 12,
              lineHeight: 1.3,
              letterSpacing: -0.3,
            }}
          >
            {item.title}
          </div>
          <div
            style={{
              fontSize: 13,
              color: theme.textDim,
              marginTop: 8,
              lineHeight: 1.55,
              fontFamily: FONTS.ui,
            }}
          >
            {item.body}
          </div>

          <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
            <button
              style={{
                flex: 1,
                background: theme.text,
                color: theme.bg,
                border: "none",
                padding: "11px 14px",
                borderRadius: 12,
                fontFamily: FONTS.ui,
                fontSize: 13,
                fontWeight: 500,
                cursor: "pointer",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                gap: 6,
              }}
            >
              {item.action} <Ico.arrowUR size={12} stroke={theme.bg} />
            </button>
            <button
              style={{
                background: "transparent",
                color: theme.textDim,
                border: `0.5px solid ${theme.line2}`,
                padding: "11px 14px",
                borderRadius: 12,
                fontFamily: FONTS.ui,
                fontSize: 13,
                cursor: "pointer",
              }}
            >
              Dismiss
            </button>
          </div>
        </Card>
      ))}
    </>
  );
}

function WealthAdvisorReferralCard({ theme }) {
  return (
    <Card theme={theme} padded={false} style={{ padding: 18 }}>
      <SectionLabel theme={theme}>
        Wealth mgmt/investment advisor referral
      </SectionLabel>
      <div
        style={{
          fontFamily: FONTS.display,
          fontSize: 17,
          color: theme.text,
          marginTop: 8,
          lineHeight: 1.3,
          letterSpacing: 0,
          fontWeight: 600,
        }}
      >
        Consult an expert
      </div>
      <div
        style={{
          fontSize: 13,
          color: theme.textDim,
          marginTop: 8,
          lineHeight: 1.55,
          fontFamily: FONTS.ui,
        }}
      >
        Discuss a professional wealth plan with a licensed advisor.
      </div>
      <button
        style={{
          width: "100%",
          background: theme.text,
          color: theme.bg,
          border: "none",
          padding: "11px 14px",
          borderRadius: 12,
          fontFamily: FONTS.ui,
          fontSize: 13,
          fontWeight: 500,
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          gap: 6,
          marginTop: 14,
        }}
      >
        Book Free Session <Ico.arrowUR size={12} stroke={theme.bg} />
      </button>
    </Card>
  );
}

function InsightProductScreen({ theme, accent, productKey, onBack }) {
  const product =
    INSIGHT_PRODUCTS.find((p) => p.key === productKey) || INSIGHT_PRODUCTS[0];

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

      <div style={{ padding: "0 16px 24px" }}>
        <div style={{ padding: "4px 6px 18px" }}>
          <div
            style={{
              fontFamily: FONTS.display,
              fontSize: 30,
              lineHeight: 1.05,
              letterSpacing: 0,
              color: theme.text,
              marginTop: 5,
              fontWeight: 600,
            }}
          >
            {product.title}
          </div>
          <div
            style={{
              marginTop: 10,
              fontFamily: FONTS.ui,
              fontSize: 14,
              lineHeight: 1.5,
              color: theme.textDim,
            }}
          >
            {product.summary}
          </div>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {product.useCases.map((item) => (
            <ProductUseCaseCard
              key={item.title}
              item={item}
              theme={theme}
              accent={product.tone || accent}
            />
          ))}
        </div>
      </div>
    </Screen>
  );
}

function RecommendationsScreen({
  theme,
  accent,
  onOpenPaywall,
  onNav,
  onAskHimma,
}) {
  const [filterKey, setFilterKey] = React.useState("all");
  const activeFilter =
    INSIGHT_FILTERS.find((filter) => filter.key === filterKey) ||
    INSIGHT_FILTERS[0];
  const activeProduct = activeFilter.productKey
    ? INSIGHT_PRODUCTS.find((p) => p.key === activeFilter.productKey)
    : null;
  const list = activeProduct
    ? []
    : activeFilter.key === "all"
      ? RECOMMENDATIONS
      : RECOMMENDATIONS.filter((r) =>
          (activeFilter.categories || []).includes(r.category),
        );

  const impactColor = (i) =>
    i === "High" ? accent : i === "Medium" ? theme.textDim : theme.textMute;
  const midnight = isMidnightInsightsTheme(theme);

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

      {/* Filters */}
      <div style={{ padding: "8px 16px 14px" }}>
        <Card
          theme={theme}
          padded={false}
          style={{
            background: midnight ? theme.surface : INSIGHT_FILTER_PANEL_BG,
            border: midnight ? `0.5px solid ${theme.line}` : "none",
            borderRadius: 22,
            padding: 14,
          }}
        >
          <div
            style={{
              display: "grid",
              gridTemplateColumns: "repeat(3, minmax(0, 1fr))",
              gap: "12px 10px",
            }}
          >
            {INSIGHT_FILTERS.map((filter) => (
              <InsightFilterTile
                key={filter.key}
                filter={filter}
                active={filterKey === filter.key}
                onClick={() => setFilterKey(filter.key)}
                theme={theme}
                accent={accent}
              />
            ))}
          </div>
        </Card>
      </div>

      {/* Cards */}
      <div
        style={{
          padding: "0 16px",
          display: "flex",
          flexDirection: "column",
          gap: 12,
        }}
      >
        {activeProduct ? (
          <InlineInsightProduct
            product={activeProduct}
            theme={theme}
            accent={accent}
          />
        ) : (
          list.map((r) => (
            <Card
              key={r.id}
              theme={theme}
              padded={false}
              style={{ padding: 18 }}
            >
              <div
                style={{
                  fontFamily: FONTS.display,
                  fontSize: 17,
                  color: theme.text,
                  marginTop: 12,
                  lineHeight: 1.3,
                  letterSpacing: -0.3,
                }}
              >
                {dhText(r.headline)}
              </div>
              <div
                style={{
                  fontSize: 13,
                  color: theme.textDim,
                  marginTop: 8,
                  lineHeight: 1.55,
                  fontFamily: FONTS.ui,
                }}
              >
                {dhText(r.body)}
              </div>

              <div
                style={{
                  marginTop: 14,
                  padding: "10px 12px",
                  background: theme.surface2,
                  borderRadius: 10,
                  display: "flex",
                  alignItems: "center",
                  gap: 10,
                }}
              >
                <Ico.sparkle size={13} stroke={accent} />
                <span
                  style={{
                    fontFamily: FONTS.mono,
                    fontSize: 11,
                    color: theme.text,
                    letterSpacing: 0.2,
                  }}
                >
                  {dhText(r.meta)}
                </span>
              </div>

              <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
                <button
                  style={{
                    flex: 1,
                    background: theme.text,
                    color: theme.bg,
                    border: "none",
                    padding: "11px 14px",
                    borderRadius: 12,
                    fontFamily: FONTS.ui,
                    fontSize: 13,
                    fontWeight: 500,
                    cursor: "pointer",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    gap: 6,
                  }}
                >
                  {r.cta} <Ico.arrowUR size={12} stroke={theme.bg} />
                </button>
                <button
                  style={{
                    background: "transparent",
                    color: theme.textDim,
                    border: `0.5px solid ${theme.line2}`,
                    padding: "11px 14px",
                    borderRadius: 12,
                    fontFamily: FONTS.ui,
                    fontSize: 13,
                    cursor: "pointer",
                  }}
                >
                  Dismiss
                </button>
              </div>
            </Card>
          ))
        )}

        {activeFilter.key === "investments" && (
          <WealthAdvisorReferralCard theme={theme} />
        )}

        {/* Peer comparison teaser */}
        <button
          onClick={() => onNav && onNav("compare")}
          style={{
            background: theme.surface,
            border: `0.5px solid ${theme.line2}`,
            borderRadius: 16,
            padding: 16,
            cursor: "pointer",
            textAlign: "left",
            color: theme.text,
            marginTop: 4,
            display: "flex",
            alignItems: "center",
            gap: 12,
          }}
        >
          <div
            style={{
              width: 36,
              height: 36,
              borderRadius: 18,
              background: `${accent}15`,
              color: accent,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
            }}
          >
            <Ico.chart size={16} />
          </div>
          <div style={{ flex: 1 }}>
            <SectionLabel theme={theme}>How you compare</SectionLabel>
            <div
              style={{
                fontFamily: FONTS.display,
                fontSize: 14.5,
                color: theme.text,
                marginTop: 4,
                lineHeight: 1.3,
              }}
            >
              See where you stand vs. peers in your age, gender and income group
            </div>
          </div>
          <Ico.chevR size={15} stroke={theme.textDim} />
        </button>
      </div>

      <div style={{ height: 10 }} />
    </Screen>
  );
}

Object.assign(window, { RecommendationsScreen, InsightProductScreen });
