"use client";

import { useMemo, useState } from "react";

type Tab = "gold" | "budget" | "emi" | "tax";

const tabs: { id: Tab; label: string }[] = [
  { id: "gold", label: "Gold & savings" },
  { id: "budget", label: "Budget split" },
  { id: "emi", label: "EMI & affordability" },
  { id: "tax", label: "Tax estimate" },
];

export default function ToolsCalculator() {
  const [activeTab, setActiveTab] = useState<Tab>("gold");

  return (
    <div
      className="
        mt-[60px]
        overflow-hidden
        rounded-[24px]
        border
        border-[#ebe4ee]
        bg-[#FEFEFE]
        shadow-[0_22px_55px_rgba(48,0,52,0.10)]
        md:mt-[72px]
        max-w-[1180px]
        mx-auto
        mb-[60px]
        lg:mb-[120px]
      "
    >
      {/* Tabs */}
      <div
        className="
          overflow-x-auto
          border-b
          border-[#e7dfe9]
          bg-[#f8f3fb]
          [scrollbar-width:none]
          [&::-webkit-scrollbar]:hidden
        "
      >
        <div className="flex min-w-max px-3 sm:px-4">
          {tabs.map((tab) => {
            const active = activeTab === tab.id;

            return (
              <button
                key={tab.id}
                type="button"
                onClick={() => setActiveTab(tab.id)}
                className={`
                  relative
                  min-h-[46px]
                  whitespace-nowrap
                  rounded-t-[16px]
                  px-4
                  text-[13px]
                  font-semibold
                  transition-all
                  duration-300
                  sm:px-5
                  md:px-6
                  md:mt-3

                  ${
                    active
                      ? "bg-white text-[#250022]"
                      : "text-[#675a6c] hover:text-[#250022]"
                  }
                `}
              >
                {/* active gradient line */}
                <span
                  className={`
                    absolute
                    left-[14px]
                    right-[14px]
                    top-0
                    h-[2px]
                    origin-left
                    rounded-full
                    bg-gradient-to-r
                    from-[#9927e3]
                    via-[#ec008c]
                    to-[#ff6a23]
                    transition-transform
                    duration-300
                    ${
                      active
                        ? "scale-x-100"
                        : "scale-x-0"
                    }
                  `}
                />

                {tab.label}
              </button>
            );
          })}
        </div>
      </div>

      {activeTab === "gold" && <GoldCalculator />}
      {activeTab === "budget" && <BudgetCalculator />}
      {activeTab === "emi" && <EmiCalculator />}
      {activeTab === "tax" && <TaxCalculator />}
    </div>
  );
}

/* =========================================================
   GOLD & SAVINGS
========================================================= */

function GoldCalculator() {
  const [monthly, setMonthly] = useState(10000);
  const [years, setYears] = useState(15);
  const [returnRate, setReturnRate] = useState(3.5);

  const result = useMemo(() => {
    const months = years * 12;
    const monthlyRate = returnRate / 100 / 12;

    const invested = monthly * months;

    let futureValue = invested;

    if (monthlyRate > 0) {
      futureValue =
        monthly *
        (((1 + monthlyRate) ** months - 1) / monthlyRate) *
        (1 + monthlyRate);
    }

    return {
      invested,
      futureValue,
      growth: Math.max(futureValue - invested, 0),
    };
  }, [monthly, years, returnRate]);

  const investedPercent =
    result.futureValue > 0
      ? (result.invested / result.futureValue) * 100
      : 0;

  const growthPercent =
    result.futureValue > 0
      ? (result.growth / result.futureValue) * 100
      : 0;

  return (
    <CalculatorLayout
      left={
        <>
          <ControlHeader
            label="Monthly investment"
            value={formatCurrency(monthly)}
          />

          <Range
            min={500}
            max={25000}
            step={500}
            value={monthly}
            onChange={setMonthly}
          />

          <PresetRow
            options={[500, 2000, 5000, 10000]}
            value={monthly}
            onChange={setMonthly}
            format={(value) => formatCurrency(value)}
          />

          <div className="mt-7">
            <ControlHeader
              label="For how long"
              value={`${years} years`}
            />

            <Range
              min={1}
              max={30}
              step={1}
              value={years}
              onChange={setYears}
            />
          </div>

          <div className="mt-7">
            <ControlHeader
              label="Assumed annual return"
              value={`${returnRate.toFixed(1)}%`}
            />

            <Range
              min={1}
              max={12}
              step={0.5}
              value={returnRate}
              onChange={setReturnRate}
            />
          </div>
        </>
      }
      right={
        <>
          <ResultHero
            label={`Estimated value after ${years} years`}
            value={formatLakh(result.futureValue)}
          />

          <SummaryGrid
            items={[
              {
                label: "You invest",
                value: formatLakh(result.invested),
              },
              {
                label: "Estimated growth",
                value: formatLakh(result.growth),
              },
              {
                label: "Monthly",
                value: formatCurrency(monthly),
              },
            ]}
          />

          <ResultBar
            label="Amount you invest"
            value={formatLakh(result.invested)}
            percent={investedPercent}
            color="bg-[#8e2bd1]"
          />

          <ResultBar
            label="Estimated growth"
            value={formatLakh(result.growth)}
            percent={growthPercent}
            color="bg-[#eb008c]"
          />

          <Legend
            items={[
              { color: "bg-[#8e2bd1]", text: "Amount you invest" },
              { color: "bg-[#eb008c]", text: "Estimated growth" },
            ]}
          />

          <Disclaimer>
            Illustrative only. Assumes a steady {returnRate.toFixed(1)}% annual
            return compounded monthly; actual returns vary and are not
            guaranteed. Not financial advice.
          </Disclaimer>
        </>
      }
    />
  );
}

/* =========================================================
   BUDGET SPLIT
========================================================= */

function BudgetCalculator() {
  const [income, setIncome] = useState(45000);
  const [needs, setNeeds] = useState(50);
  const [wants, setWants] = useState(30);

  const saving = Math.max(100 - needs - wants, 0);

  const needsAmount = income * (needs / 100);
  const wantsAmount = income * (wants / 100);
  const savingAmount = income * (saving / 100);

  return (
    <CalculatorLayout
      left={
        <>
          <ControlHeader
            label="Monthly take-home"
            value={formatCurrency(income)}
          />

          <Range
            min={25000}
            max={200000}
            step={1000}
            value={income}
            onChange={setIncome}
          />

          <PresetRow
            options={[25000, 45000, 100000, 200000]}
            value={income}
            onChange={setIncome}
            format={(value) =>
              value >= 100000
                ? `₹${value / 100000}L`
                : `₹${value / 1000}k`
            }
          />

          <div className="mt-7">
            <ControlHeader label="Needs" value={`${needs}%`} />

            <Range
              min={20}
              max={70}
              step={1}
              value={needs}
              onChange={(value) =>
                setNeeds(Math.min(value, 100 - wants))
              }
            />
          </div>

          <div className="mt-7">
            <ControlHeader label="Wants" value={`${wants}%`} />

            <Range
              min={5}
              max={60}
              step={1}
              value={wants}
              onChange={(value) =>
                setWants(Math.min(value, 100 - needs))
              }
            />
          </div>

          <p className="mt-7 text-[11px] leading-[1.65] text-[#887b8d]">
            Savings takes whatever remains. The classic split is 50 / 30 / 20
            — move the sliders to fit your real life.
          </p>
        </>
      }
      right={
        <>
          <ResultHero
            label="Towards saving and investing each month"
            value={formatCurrency(savingAmount)}
          />

          <SummaryGrid
            items={[
              { label: "Needs", value: formatCurrency(needsAmount) },
              { label: "Wants", value: formatCurrency(wantsAmount) },
              {
                label: "In a year",
                value: formatLakh(savingAmount * 12),
              },
            ]}
          />

          <ResultBar
            label={`Needs · ${needs}%`}
            value={formatCurrency(needsAmount)}
            percent={needs}
            color="bg-[#8e2bd1]"
          />

          <ResultBar
            label={`Wants · ${wants}%`}
            value={formatCurrency(wantsAmount)}
            percent={wants}
            color="bg-[#ff7b20]"
          />

          <ResultBar
            label={`Save · ${saving}%`}
            value={formatCurrency(savingAmount)}
            percent={saving}
            color="bg-[#eb008c]"
          />

          <Legend
            items={[
              { color: "bg-[#8e2bd1]", text: `Needs · ${needs}%` },
              { color: "bg-[#ff7b20]", text: `Wants · ${wants}%` },
              { color: "bg-[#eb008c]", text: `Save · ${saving}%` },
            ]}
          />

          <Disclaimer>
            A guide, not a rule. Saving {saving} points puts{" "}
            {formatLakh(savingAmount * 12)} aside over a year before any
            returns.
          </Disclaimer>
        </>
      }
    />
  );
}

/* =========================================================
   EMI
========================================================= */

function EmiCalculator() {
  const [loan, setLoan] = useState(300000);
  const [interestRate, setInterestRate] = useState(14);
  const [months, setMonths] = useState(36);
  const [income, setIncome] = useState(45000);

  const result = useMemo(() => {
    const monthlyRate = interestRate / 100 / 12;

    const emi =
      monthlyRate === 0
        ? loan / months
        : (loan *
            monthlyRate *
            (1 + monthlyRate) ** months) /
          ((1 + monthlyRate) ** months - 1);

    const totalRepayment = emi * months;
    const totalInterest = totalRepayment - loan;
    const incomeShare = income > 0 ? (emi / income) * 100 : 0;

    return {
      emi,
      totalRepayment,
      totalInterest,
      incomeShare,
    };
  }, [loan, interestRate, months, income]);

  const interestPercent =
    result.totalRepayment > 0
      ? (result.totalInterest / result.totalRepayment) * 100
      : 0;

  const principalPercent = 100 - interestPercent;

  return (
    <CalculatorLayout
      left={
        <>
          <ControlHeader
            label="Loan amount"
            value={formatCurrency(loan)}
          />

          <Range
            min={50000}
            max={2000000}
            step={10000}
            value={loan}
            onChange={setLoan}
          />

          <div className="mt-7">
            <ControlHeader
              label="Interest rate"
              value={`${interestRate}%`}
            />

            <Range
              min={5}
              max={30}
              step={0.5}
              value={interestRate}
              onChange={setInterestRate}
            />
          </div>

          <div className="mt-7">
            <ControlHeader
              label="Tenure"
              value={`${months} months`}
            />

            <Range
              min={6}
              max={84}
              step={1}
              value={months}
              onChange={setMonths}
            />
          </div>

          <div className="mt-7">
            <ControlHeader
              label="Your monthly income"
              value={formatCurrency(income)}
            />

            <Range
              min={20000}
              max={300000}
              step={1000}
              value={income}
              onChange={setIncome}
            />
          </div>
        </>
      }
      right={
        <>
          <ResultHero
            label="Your monthly EMI"
            value={formatCurrency(result.emi)}
          />

          <SummaryGrid
            items={[
              {
                label: "Total interest",
                value: formatCurrency(result.totalInterest),
              },
              {
                label: "Total repayment",
                value: formatLakh(result.totalRepayment),
              },
              {
                label: "Share of income",
                value: `${Math.round(result.incomeShare)}%`,
              },
            ]}
          />

          <ResultBar
            label="Principal"
            value={formatLakh(loan)}
            percent={principalPercent}
            color="bg-[#8e2bd1]"
          />

          <ResultBar
            label="Interest"
            value={formatCurrency(result.totalInterest)}
            percent={interestPercent}
            color="bg-[#ff7b20]"
          />

          <Legend
            items={[
              { color: "bg-[#8e2bd1]", text: "Principal" },
              { color: "bg-[#ff7b20]", text: "Interest" },
            ]}
          />

          <Disclaimer>
            This EMI is {Math.round(result.incomeShare)}% of your monthly
            income. Illustrative only, not an offer of credit.
          </Disclaimer>
        </>
      }
    />
  );
}

/* =========================================================
   TAX
========================================================= */

function TaxCalculator() {
  const [income, setIncome] = useState(1275000);

  const result = useMemo(() => {
    return calculateTaxBreakdown(income);
  }, [income]);

  const takeHome = Math.max(income - result.totalTax, 0);

  const effectiveRate =
    income > 0 ? (result.totalTax / income) * 100 : 0;

  return (
    <CalculatorLayout
      left={
        <>
          <ControlHeader
            label="Annual income"
            value={formatCurrency(income)}
          />

          <Range
            min={600000}
            max={10000000}
            step={25000}
            value={income}
            onChange={setIncome}
          />

          <PresetRow
            options={[600000, 1275000, 2400000, 5000000, 10000000]}
            value={income}
            onChange={setIncome}
            format={(value) => {
              if (value >= 10000000) {
                return `₹${value / 10000000}Cr`;
              }

              return `₹${value / 100000}L`;
            }}
          />

          <p
            className="
              mt-5
              max-w-[500px]
              text-[11px]
              leading-[1.65]
              text-[#887b8d]
              sm:mt-6
            "
          >
            New tax regime, FY 2026-27. Applies the ₹75,000 standard
            deduction for salaried income, then taxes each slab in turn.
            Includes the section 87A rebate, marginal relief, surcharge
            and 4% cess.
          </p>
        </>
      }
      right={
        <>
          <ResultHero
            label="Estimated tax for the year"
            value={formatCurrency(result.totalTax)}
          />

          <SummaryGrid
            items={[
              {
                label: "Take-home",
                value: formatCompactLakh(takeHome),
              },
              {
                label: "Effective rate",
                value: `${effectiveRate.toFixed(1)}%`,
              },
              {
                label: "Per month",
                value: formatCurrency(result.totalTax / 12),
              },
            ]}
          />

          <TaxBreakdownTable result={result} />

          <p
            className="
              mt-5
              text-[10px]
              leading-[1.65]
              text-[#776a7d]
              sm:text-[11px]
            "
          >
            Gross income {formatCurrency(income)} minus standard deduction{" "}
            {formatCurrency(result.standardDeduction)} gives taxable income
            of {formatCurrency(result.taxableIncome)}.
          </p>
        </>
      }
    />
  );
}

function TaxBreakdownTable({
  result,
}: {
  result: TaxBreakdown;
}) {
  return (
    <div className="mt-[26px] w-full">
      {/* Desktop / tablet table */}
      <div className="hidden sm:block">
        {/* Header */}
        <div
          className="
            grid
            grid-cols-[1.45fr_0.65fr_1.2fr_0.9fr]
            gap-3
            border-b
            border-[#ddd5e1]
            pb-[9px]
          "
        >
          <TaxTableHeading>Slab</TaxTableHeading>
          <TaxTableHeading>Rate</TaxTableHeading>

          <TaxTableHeading className="text-right">
            Income in slab
          </TaxTableHeading>

          <TaxTableHeading className="text-right">
            Tax
          </TaxTableHeading>
        </div>

        {/* Slab rows */}
        {result.slabs.map((slab) => (
          <div
            key={slab.label}
            className="
              grid
              grid-cols-[1.45fr_0.65fr_1.2fr_0.9fr]
              items-center
              gap-3
              border-b
              border-[#ddd5e1]
              py-[9px]
            "
          >
            <span className="text-[14px] text-[#65596c]">
              {slab.label}
            </span>

            <span className="text-[14px] font-medium text-[#250022]">
              {Math.round(slab.rate * 100)}%
            </span>

            <span className="text-right text-[14px] text-[#250022]">
              {formatCurrency(slab.incomeInSlab)}
            </span>

            <span className="text-right text-[14px] font-medium text-[#250022]">
              {formatCurrency(slab.tax)}
            </span>
          </div>
        ))}

        <TaxTotalRow
          label="Tax on slabs"
          value={formatCurrency(result.taxOnSlabs)}
          bold
        />

        {result.rebate > 0 && (
          <TaxTotalRow
            label="Less: section 87A rebate"
            value={`−${formatCurrency(result.rebate)}`}
            accent
          />
        )}

        <TaxTotalRow
          label="Add: health & education cess at 4%"
          value={formatCurrency(result.cess)}
        />

        <TaxTotalRow
          label="Total tax payable"
          value={formatCurrency(result.totalTax)}
          total
        />
      </div>

      {/* Mobile version */}
      <div className="sm:hidden">
        <div className="border-b border-[#ddd5e1] pb-2">
          <TaxTableHeading>Tax breakdown</TaxTableHeading>
        </div>

        <div className="divide-y divide-[#e1d9e4]">
          {result.slabs.map((slab) => (
            <div
              key={slab.label}
              className="py-[12px]"
            >
              <div className="flex items-center justify-between gap-4">
                <span className="text-[12px] font-medium text-[#62556a]">
                  {slab.label}
                </span>

                <span className="shrink-0 text-[12px] font-semibold text-[#250022]">
                  {Math.round(slab.rate * 100)}%
                </span>
              </div>

              <div className="mt-[7px] flex items-center justify-between gap-4">
                <span className="text-[10px] uppercase tracking-[0.12em] text-[#918494]">
                  Income in slab
                </span>

                <span className="text-[12px] text-[#250022]">
                  {formatCurrency(slab.incomeInSlab)}
                </span>
              </div>

              <div className="mt-[5px] flex items-center justify-between gap-4">
                <span className="text-[10px] uppercase tracking-[0.12em] text-[#918494]">
                  Tax
                </span>

                <span className="text-[12px] font-semibold text-[#250022]">
                  {formatCurrency(slab.tax)}
                </span>
              </div>
            </div>
          ))}
        </div>

        <div className="border-t border-[#ddd5e1]">
          <TaxMobileTotal
            label="Tax on slabs"
            value={formatCurrency(result.taxOnSlabs)}
          />

          {result.rebate > 0 && (
            <TaxMobileTotal
              label="Less: section 87A rebate"
              value={`−${formatCurrency(result.rebate)}`}
              accent
            />
          )}

          <TaxMobileTotal
            label="Add: health & education cess at 4%"
            value={formatCurrency(result.cess)}
          />

          <TaxMobileTotal
            label="Total tax payable"
            value={formatCurrency(result.totalTax)}
            total
          />
        </div>
      </div>
    </div>
  );
}

function TaxTableHeading({
  children,
  className = "",
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <span
      className={`
        text-[8px]
        font-semibold
        uppercase
        tracking-[0.22em]
        text-[#62556a]
        ${className}
      `}
    >
      {children}
    </span>
  );
}

function TaxTotalRow({
  label,
  value,
  bold = false,
  accent = false,
  total = false,
}: {
  label: string;
  value: string;
  bold?: boolean;
  accent?: boolean;
  total?: boolean;
}) {
  return (
    <div
      className={`
        flex
        items-center
        justify-between
        gap-5
        border-b
        border-[#ddd5e1]
        py-[10px]
        ${total ? "pt-[13px]" : ""}
      `}
    >
      <span
        className={`
          text-[12px]
          ${
            total
              ? "text-[14px] font-bold text-[#250022]"
              : bold
                ? "font-semibold text-[#62556a]"
                : accent
                  ? "font-medium text-[#8e22d0]"
                  : "font-medium text-[#62556a]"
          }
        `}
      >
        {label}
      </span>

      <span
        className={`
          shrink-0
          text-right
          text-[12px]
          ${
            total
              ? "text-[14px] font-bold text-[#250022]"
              : accent
                ? "font-semibold text-[#8e22d0]"
                : "font-semibold text-[#250022]"
          }
        `}
      >
        {value}
      </span>
    </div>
  );
}

function TaxMobileTotal({
  label,
  value,
  accent = false,
  total = false,
}: {
  label: string;
  value: string;
  accent?: boolean;
  total?: boolean;
}) {
  return (
    <div
      className={`
        flex
        items-start
        justify-between
        gap-4
        border-b
        border-[#ddd5e1]
        py-[11px]
        ${total ? "py-[14px]" : ""}
      `}
    >
      <span
        className={`
          max-w-[70%]
          text-[11px]
          leading-[1.4]
          ${
            total
              ? "text-[13px] font-bold text-[#250022]"
              : accent
                ? "font-medium text-[#8e22d0]"
                : "font-medium text-[#62556a]"
          }
        `}
      >
        {label}
      </span>

      <span
        className={`
          shrink-0
          text-right
          ${
            total
              ? "text-[13px] font-bold text-[#250022]"
              : accent
                ? "text-[11px] font-semibold text-[#8e22d0]"
                : "text-[11px] font-semibold text-[#250022]"
          }
        `}
      >
        {value}
      </span>
    </div>
  );
}

/* =========================================================
   SHARED UI
========================================================= */

function CalculatorLayout({
  left,
  right,
}: {
  left: React.ReactNode;
  right: React.ReactNode;
}) {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2">
      {/* Left controls */}
      <div
        className="
          min-w-0
          border-b
          border-[#e7dfe9]
          bg-white
          px-5
          py-8
          sm:px-8
          sm:py-10
          lg:min-h-[490px]
          lg:border-b-0
          lg:border-r
          lg:px-[36px]
        "
      >
        {left}
      </div>

      {/* Right results */}
      <div
        className="
          min-w-0
          bg-[#F7F3FA]
          px-5
          py-8
          sm:px-8
          sm:py-10
          lg:min-h-[490px]
          lg:px-[34px]
        "
      >
        {right}
      </div>
    </div>
  );
}

function ControlHeader({
  label,
  value,
}: {
  label: string;
  value: string;
}) {
  return (
    <div className="mb-[14px] flex items-center justify-between gap-4">
      <span
        className="
          text-[9px]
          font-semibold
          uppercase
          tracking-[0.24em]
          text-[#62556a]
        "
      >
        {label}
      </span>

      <span className="text-[14px] font-bold text-[#250022] sm:text-[15px]">
        {value}
      </span>
    </div>
  );
}

function Range({
  min,
  max,
  step,
  value,
  onChange,
}: {
  min: number;
  max: number;
  step: number;
  value: number;
  onChange: (value: number) => void;
}) {
  return (
    <div className="relative flex h-[22px] w-full items-center">
      {/* Plain slider track */}
      <div
        className="
          pointer-events-none
          absolute  
          left-0
          right-0
          h-[6px]
          rounded-full
          bg-[#eee5f4]
        "
      />

      <input
        type="range"
        min={min}
        max={max}
        step={step}
        value={value}
        onChange={(event) => onChange(Number(event.target.value))}
        className="
          relative
          z-10
          h-[22px]
          w-full
          cursor-pointer
          appearance-none
          bg-transparent
          outline-none

          [&::-webkit-slider-runnable-track]:h-[6px]
          [&::-webkit-slider-runnable-track]:rounded-full
          [&::-webkit-slider-runnable-track]:bg-transparent

          [&::-webkit-slider-thumb]:mt-[-7px]
          [&::-webkit-slider-thumb]:h-[20px]
          [&::-webkit-slider-thumb]:w-[20px]
          [&::-webkit-slider-thumb]:appearance-none
          [&::-webkit-slider-thumb]:rounded-full
          [&::-webkit-slider-thumb]:border-[2px]
          [&::-webkit-slider-thumb]:border-[#ef008c]
          [&::-webkit-slider-thumb]:bg-white
          [&::-webkit-slider-thumb]:shadow-[0_4px_10px_rgba(235,0,140,0.20)]

          [&::-moz-range-track]:h-[6px]
          [&::-moz-range-track]:rounded-full
          [&::-moz-range-track]:bg-transparent

          [&::-moz-range-progress]:bg-transparent

          [&::-moz-range-thumb]:h-[18px]
          [&::-moz-range-thumb]:w-[18px]
          [&::-moz-range-thumb]:rounded-full
          [&::-moz-range-thumb]:border-[2px]
          [&::-moz-range-thumb]:border-[#ef008c]
          [&::-moz-range-thumb]:bg-white
          [&::-moz-range-thumb]:shadow-[0_4px_10px_rgba(235,0,140,0.20)]

          focus-visible:[&::-webkit-slider-thumb]:ring-4
          focus-visible:[&::-webkit-slider-thumb]:ring-[#ef008c]/15
          focus-visible:[&::-moz-range-thumb]:ring-4
          focus-visible:[&::-moz-range-thumb]:ring-[#ef008c]/15
        "
        aria-valuemin={min}
        aria-valuemax={max}
        aria-valuenow={value}
      />
    </div>
  );
}

function PresetRow({
  options,
  value,
  onChange,
  format,
}: {
  options: number[];
  value: number;
  onChange: (value: number) => void;
  format: (value: number) => string;
}) {
  return (
    <div className="mt-[10px] flex flex-wrap gap-2">
      {options.map((option) => {
        const active = option === value;

        return (
          <button
            key={option}
            type="button"
            onClick={() => onChange(option)}
            className={`
              min-h-[34px]
              rounded-full
              border
              px-3
              text-[13px]
              font-semibold
              transition-all
              duration-200

              ${
                active
                  ? "border-transparent bg-gradient-to-r from-[#9e28dc] to-[#ef008c] text-white"
                  : "border-[#ded5e2] bg-white text-[#64586a] hover:border-[#c99dd7]"
              }
            `}
          >
            {format(option)}
          </button>
        );
      })}
    </div>
  );
}

function ResultHero({
  label,
  value,
}: {
  label: string;
  value: string;
}) {
  return (
    <>
      <p
        className="
          text-[9px]
          font-semibold
          uppercase
          tracking-[0.24em]
          text-[#62556a]
        "
      >
        {label}
      </p>

      <div
        className="
          mt-[8px]
          bg-gradient-to-r
          from-[#9929d6]
          via-[#bf16b7]
          to-[#db069b]
          bg-clip-text
          text-[42px]
          font-[800]
          leading-none
          tracking-[-0.055em]
          text-transparent
          transition-all
          duration-300
          sm:text-[48px]
        "
      >
        {value}
      </div>
    </>
  );
}

function SummaryGrid({
  items,
}: {
  items: {
    label: string;
    value: string;
  }[];
}) {
  return (
    <div
      className="
        mt-[24px]
        grid
        grid-cols-1
        gap-5
        border-t
        border-[#e9e1eb]
        pt-[20px]
        sm:grid-cols-3
      "
    >
      {items.map((item) => (
        <div key={item.label}>
          <p
            className="
              text-[8px]
              font-semibold
              uppercase
              tracking-[0.2em]
              text-[#62556a]
            "
          >
            {item.label}
          </p>

          <p
            className="
              mt-[8px]
              text-[19px]
              font-[700]
              text-[#250022]
              transition-all
              duration-300
            "
          >
            {item.value}
          </p>
        </div>
      ))}
    </div>
  );
}

function ResultBar({
  label,
  value,
  percent,
  color,
}: {
  label: string;
  value: string;
  percent: number;
  color: string;
}) {
  return (
    <div className="mt-[28px]">
      <div className="mb-[7px] flex items-end justify-between gap-4">
        <span className="text-[16px] font-medium text-[#665a6d]">
          {label}
        </span>

        <span className="shrink-0 text-[15px] font-bold text-[#250022]">
          {value}
        </span>
      </div>

      <div className="h-[13px] overflow-hidden rounded-full bg-[#eee5f4]">
        <div
          className={`
            h-full
            rounded-full
            transition-[width]
            duration-500
            ease-out
            ${color}
          `}
          style={{
            width: `${Math.min(Math.max(percent, 0), 100)}%`,
          }}
        />
      </div>
    </div>
  );
}

function Legend({
  items,
}: {
  items: {
    color: string;
    text: string;
  }[];
}) {
  return (
    <div className="mt-[34px] flex flex-wrap justify-center gap-x-5 gap-y-2">
      {items.map((item) => (
        <div
          key={item.text}
          className="flex items-center gap-[7px] text-[11px] text-[#6c6072]"
        >
          <span className={`h-[10px] w-[10px] rounded-[3px] ${item.color}`} />
          {item.text}
        </div>
      ))}
    </div>
  );
}

function Disclaimer({ children }: { children: React.ReactNode }) {
  return (
    <p
      className="
        mt-[24px]
        border-t
        border-[#e9e1eb]
        pt-[17px]
        text-[10px]
        leading-[1.65]
        text-[#8d808f]
        sm:text-[11px]
      "
    >
      {children}
    </p>
  );
}

/* =========================================================
   FORMATTERS / CALCULATIONS
========================================================= */

function formatCurrency(value: number) {
  return new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    maximumFractionDigits: 0,
  }).format(Math.round(value));
}

function formatLakh(value: number) {
  if (value >= 10000000) {
    return `₹${(value / 10000000).toFixed(2)} Cr`;
  }

  if (value >= 100000) {
    return `₹${(value / 100000).toFixed(2)} L`;
  }

  return formatCurrency(value);
}

function formatCompactLakh(value: number) {
  if (value >= 10000000) {
    const crores = value / 10000000;

    return `₹${Number(crores.toFixed(2))} Cr`;
  }

  if (value >= 100000) {
    const lakhs = value / 100000;

    return `₹${Number(lakhs.toFixed(2))} L`;
  }

  return formatCurrency(value);
}

type TaxSlabRow = {
  label: string;
  rate: number;
  incomeInSlab: number;
  tax: number;
};

type TaxBreakdown = {
  standardDeduction: number;
  taxableIncome: number;
  slabs: TaxSlabRow[];
  taxOnSlabs: number;
  rebate: number;
  taxAfterRebate: number;
  cess: number;
  totalTax: number;
};

function calculateTaxBreakdown(income: number): TaxBreakdown {
  const standardDeduction = 75000;
  const taxableIncome = Math.max(income - standardDeduction, 0);

  const slabDefinitions = [
    {
      from: 0,
      to: 400000,
      rate: 0,
      label: "₹0L to ₹4L",
    },
    {
      from: 400000,
      to: 800000,
      rate: 0.05,
      label: "₹4L to ₹8L",
    },
    {
      from: 800000,
      to: 1200000,
      rate: 0.1,
      label: "₹8L to ₹12L",
    },
    {
      from: 1200000,
      to: 1600000,
      rate: 0.15,
      label: "₹12L to ₹16L",
    },
    {
      from: 1600000,
      to: 2000000,
      rate: 0.2,
      label: "₹16L to ₹20L",
    },
    {
      from: 2000000,
      to: 2400000,
      rate: 0.25,
      label: "₹20L to ₹24L",
    },
    {
      from: 2400000,
      to: Infinity,
      rate: 0.3,
      label: "Above ₹24L",
    },
  ];

  const slabs: TaxSlabRow[] = slabDefinitions
    .map((slab) => {
      const incomeInSlab =
        taxableIncome > slab.from
          ? Math.min(taxableIncome, slab.to) - slab.from
          : 0;

      const tax = incomeInSlab * slab.rate;

      return {
        label: slab.label,
        rate: slab.rate,
        incomeInSlab: Math.max(incomeInSlab, 0),
        tax: Math.max(tax, 0),
      };
    })
    .filter((slab) => slab.incomeInSlab > 0);

  const taxOnSlabs = slabs.reduce(
    (total, slab) => total + slab.tax,
    0
  );

  /*
   * Matches the ₹12.75L screenshot:
   * ₹12L taxable income produces ₹60,000 slab tax,
   * which is fully offset by Section 87A rebate.
   */
  const rebate =
    taxableIncome <= 1200000
      ? Math.min(taxOnSlabs, 60000)
      : 0;

  const taxAfterRebate = Math.max(taxOnSlabs - rebate, 0);

  const cess = taxAfterRebate * 0.04;

  const totalTax = taxAfterRebate + cess;

  return {
    standardDeduction,
    taxableIncome,
    slabs,
    taxOnSlabs: Math.round(taxOnSlabs),
    rebate: Math.round(rebate),
    taxAfterRebate: Math.round(taxAfterRebate),
    cess: Math.round(cess),
    totalTax: Math.round(totalTax),
  };
}