/* nro.jsx — National Revenue Office chrome.
   Adds a working (demo) Sign In: account data is gated behind it.
   Signed-out → "Sign in to view your account" + locked service tiles.
   Signed-in  → populated account + clickable tiles open simple views.
   Nav tabs and service tiles are all navigable. */

const NRO_NAV = ["Home", "File a Return", "Payments", "Refunds", "Help"];

/* The signed-in taxpayer. One identity, four places: the profile in the backend's
   seed.json, NRO_DEMO_TAXPAYER/NRO_DEMO_USER on the chat app, the `_user` on every
   gateway log line — and now the portal chrome. Keep them in step: the point of the
   demo is that the person in the header is the person the gateway is billing and
   the person every tool is scoped to. */
const NRO_USER = {
  name: "Lukas Weber",
  handle: "LukasW@nro",
  initials: "LW",
  steuerId: "65 929 970 489",
};

const NRO_ACCOUNT = [
  ["Tax year", "2025"],
  ["Refund status", "Approved — Jun 9"],
  ["Balance due", "€0.00"],
];

const NRO_FORMS = [
  { code: "Form 1040", name: "Individual Income Tax Return", note: "The standard annual return for individuals." },
  { code: "Schedule C", name: "Profit or Loss from Business", note: "Report freelance or self-employment income." },
  { code: "Form 4868", name: "Application for Extension", note: "Request a 6-month filing extension to Oct 15." },
  { code: "Form 8822", name: "Change of Address", note: "Update the mailing address on your account." },
];

const NRO_DEADLINES = [
  { date: "Apr 15, 2026", title: "Individual returns due", note: "Form 1040 filing and payment deadline." },
  { date: "Jun 16, 2026", title: "Q2 estimated tax", note: "Second estimated payment for the year." },
  { date: "Oct 15, 2026", title: "Extended filing deadline", note: "For taxpayers who filed Form 4868." },
];

function NroPanel({ t, children, className = "" }) {
  return <div className={"rounded-lg p-5 " + className} style={{ background: t.surface, border: `1px solid ${t.line}` }}>{children}</div>;
}

function NroBack({ t, onClick }) {
  return (
    <button onClick={onClick} className="mb-3 inline-flex items-center gap-1.5 text-[13px] font-semibold" style={{ color: t.primary }}>
      <Icon name="ArrowLeft" size={15} /> Back to services
    </button>
  );
}

function NroSignInForm({ t, onSignIn, onClose }) {
  const [id, setId] = React.useState("");
  const [pin, setPin] = React.useState("");
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ background: "rgba(15,37,65,0.45)", backdropFilter: "blur(3px)" }} onClick={onClose}>
      <div className="w-full max-w-[400px] rounded-xl p-6" style={{ background: t.surface, border: `1px solid ${t.line}`, boxShadow: "0 30px 70px -30px rgba(15,37,65,0.6)" }} onClick={(e) => e.stopPropagation()}>
        <div className="flex items-center gap-2.5">
          <span className="flex h-10 w-10 items-center justify-center rounded-lg" style={{ background: t.primary, color: t.gold }}><Icon name="ShieldCheck" size={20} /></span>
          <div>
            <h2 className="text-[18px] font-bold" style={{ fontFamily: t.headingFont }}>Sign in to your account</h2>
            <p className="text-[12px]" style={{ color: t.sub }}>Secure taxpayer authentication</p>
          </div>
        </div>
        <form onSubmit={(e) => { e.preventDefault(); onSignIn(); }} className="mt-5 space-y-3">
          <label className="block">
            <span className="text-[12px] font-semibold" style={{ color: t.sub }}>Taxpayer ID</span>
            <input value={id} onChange={(e) => setId(e.target.value)} placeholder="e.g. 65 929 970 489" className="mt-1 w-full rounded-lg px-3 py-2.5 text-[14px] outline-none" style={{ background: t.surfaceAlt, border: `1px solid ${t.line}`, color: t.ink }} />
          </label>
          <label className="block">
            <span className="text-[12px] font-semibold" style={{ color: t.sub }}>PIN / Password</span>
            <input value={pin} onChange={(e) => setPin(e.target.value)} type="password" placeholder="••••••" className="mt-1 w-full rounded-lg px-3 py-2.5 text-[14px] outline-none" style={{ background: t.surfaceAlt, border: `1px solid ${t.line}`, color: t.ink }} />
          </label>
          <p className="flex items-center gap-1.5 text-[11.5px]" style={{ color: t.sub }}>
            <Icon name="Info" size={13} style={{ color: t.gold }} /> Demo only — any value signs you in.
          </p>
          <button type="submit" className="w-full rounded-lg px-4 py-3 text-[14px] font-bold" style={{ background: t.primary, color: "#fff" }}>Sign in securely</button>
        </form>
      </div>
    </div>
  );
}

function NroTileView({ t, view, signedIn }) {
  if (view === "refund") {
    return (
      <div className="space-y-3">
        <div className="rounded-lg p-5" style={{ background: `linear-gradient(120deg, ${t.heroFrom}, ${t.heroTo})`, color: "#fff" }}>
          <p className="text-[12px] uppercase tracking-wide opacity-80">Refund status</p>
          <p className="mt-1 text-[22px] font-bold" style={{ fontFamily: t.headingFont }}>Approved</p>
          <p className="mt-0.5 text-[13.5px] opacity-90">Scheduled for direct deposit on Jun 9, 2026.</p>
        </div>
        <NroPanel t={t}>
          {[["Refund amount", "€1,240.00"], ["Method", "Direct deposit ••• 4471"], ["Approved on", "Jun 1, 2026"], ["Tax year", "2025"]].map(([l, v]) => (
            <div key={l} className="flex items-center justify-between border-b py-2.5 text-[13.5px] last:border-0" style={{ borderColor: t.line }}><span style={{ color: t.sub }}>{l}</span><span className="font-semibold">{v}</span></div>
          ))}
        </NroPanel>
      </div>
    );
  }
  if (view === "payment") {
    return (
      <NroPanel t={t}>
        <h3 className="text-[16px] font-bold" style={{ fontFamily: t.headingFont }}>Make a payment</h3>
        <div className="mt-3 flex items-center justify-between rounded-lg p-3" style={{ background: t.surfaceAlt }}>
          <span className="text-[13.5px]" style={{ color: t.sub }}>Current balance due</span><span className="text-[18px] font-bold">€0.00</span>
        </div>
        <p className="mt-3 flex items-center gap-2 text-[13px]" style={{ color: t.accent }}><Icon name="CheckCircle2" size={16} /> Your account is paid in full. No payment is due.</p>
        <button className="mt-4 w-full rounded-lg px-4 py-3 text-[14px] font-bold opacity-50" style={{ background: t.primary, color: "#fff" }} disabled>Nothing to pay</button>
      </NroPanel>
    );
  }
  if (view === "forms") {
    return (
      <div className="space-y-3">
        {NRO_FORMS.map((f) => (
          <NroPanel t={t} key={f.code}>
            <div className="flex items-center gap-3">
              <span className="flex h-10 w-10 items-center justify-center rounded-md" style={{ background: t.tintBubble, color: t.primary }}><Icon name="FileText" size={18} /></span>
              <div className="flex-1"><div className="text-[14px] font-bold">{f.code}</div><div className="text-[12.5px]" style={{ color: t.sub }}>{f.name}</div></div>
              <Icon name="Download" size={17} style={{ color: t.sub }} />
            </div>
            <p className="mt-2 text-[12.5px]" style={{ color: t.sub }}>{f.note}</p>
          </NroPanel>
        ))}
      </div>
    );
  }
  if (view === "deadlines") {
    return (
      <div className="space-y-3">
        {NRO_DEADLINES.map((d) => (
          <NroPanel t={t} key={d.title}>
            <div className="flex items-center gap-3.5">
              <span className="flex h-11 w-11 items-center justify-center rounded-lg" style={{ background: t.tintBubble, color: t.primary }}><Icon name="CalendarClock" size={19} /></span>
              <div className="flex-1"><div className="text-[14px] font-bold">{d.title}</div><div className="text-[12.5px]" style={{ color: t.sub }}>{d.note}</div></div>
              <span className="text-[13px] font-semibold" style={{ color: t.primary }}>{d.date}</span>
            </div>
          </NroPanel>
        ))}
      </div>
    );
  }
  if (view === "file") {
    return (
      <NroPanel t={t}>
        <h3 className="text-[16px] font-bold" style={{ fontFamily: t.headingFont }}>File a return</h3>
        <p className="mt-1 text-[13px]" style={{ color: t.sub }}>Tax year 2025 · Form 1040</p>
        <div className="mt-4 space-y-2.5">
          {[["Personal details", "complete"], ["Income & wages", "complete"], ["Deductions & credits", "in progress"], ["Review & submit", "todo"]].map(([step, st], i) => (
            <div key={step} className="flex items-center gap-3 rounded-lg p-3" style={{ background: t.surfaceAlt }}>
              <span className="flex h-7 w-7 items-center justify-center rounded-full text-[12px] font-bold" style={{ background: st === "complete" ? t.accent : st === "in progress" ? t.gold : t.line, color: st === "todo" ? t.sub : "#fff" }}>{st === "complete" ? "✓" : i + 1}</span>
              <span className="flex-1 text-[13.5px] font-semibold">{step}</span>
              <span className="text-[11px] font-semibold uppercase tracking-wide" style={{ color: t.sub }}>{st}</span>
            </div>
          ))}
        </div>
        <button className="mt-4 w-full rounded-lg px-4 py-3 text-[14px] font-bold" style={{ background: t.primary, color: "#fff" }}>Continue filing</button>
      </NroPanel>
    );
  }
  if (view === "help") {
    return (
      <div className="space-y-3">
        <NroPanel t={t}>
          <h3 className="text-[16px] font-bold" style={{ fontFamily: t.headingFont }}>Help & FAQs</h3>
          <div className="mt-3 divide-y" style={{ borderColor: t.line }}>
            {["Wo bleibt meine Erstattung?", "Wie richte ich eine Ratenzahlung ein?", "Welches Formular brauche ich für freiberufliche Einkünfte?", "Wie ändere ich meine Postanschrift?"].map((q) => (
              <div key={q} className="flex items-center justify-between py-2.5 text-[13.5px]"><span>{q}</span><Icon name="ChevronRight" size={16} style={{ color: t.sub }} /></div>
            ))}
          </div>
        </NroPanel>
        <p className="flex items-center gap-2 text-[13px]" style={{ color: t.sub }}><Icon name="ArrowRight" size={15} style={{ color: t.primary }} /> Ask Nora in the panel on the right for anything else.</p>
      </div>
    );
  }
  return null;
}

function NroChrome({ business, children }) {
  const t = business.theme;
  const [signedIn, setSignedIn] = React.useState(false);
  const [showSignIn, setShowSignIn] = React.useState(false);
  const [view, setView] = React.useState("home"); // home | refund | payment | forms | deadlines | file | help
  const [pending, setPending] = React.useState(null);

  // Map nav tab + service tile → internal view, gating where account data is involved
  const GATED = new Set(["refund", "payment", "file", "account"]);
  function navTo(target) {
    if (GATED.has(target) && !signedIn) { setPending(target); setShowSignIn(true); return; }
    setView(target);
  }
  function handleSignIn() {
    setSignedIn(true);
    setShowSignIn(false);
    if (pending) { setView(pending === "account" ? "home" : pending); setPending(null); }
  }

  const TILES = [
    ["Receipt", "Check refund", "refund"],
    ["HandCoins", "Make a payment", "payment"],
    ["FileText", "Find a form", "forms"],
    ["CalendarClock", "Deadlines", "deadlines"],
  ];
  const NAV_VIEW = { "Home": "home", "File a Return": "file", "Payments": "payment", "Refunds": "refund", "Help": "help" };
  const VIEW_NAV = { home: "Home", file: "File a Return", payment: "Payments", refund: "Refunds", help: "Help" };

  const titleFor = { refund: "Check refund", payment: "Make a payment", forms: "Find a form", deadlines: "Deadlines", file: "File a return", help: "Help" };

  return (
    <div className="min-h-full" style={{ background: t.page, color: t.ink, fontFamily: t.font }}>
      <div className="flex items-center justify-center gap-2 px-6 py-1.5 text-[11.5px]" style={{ background: t.primaryDeep, color: "rgba(255,255,255,0.92)" }}>
        <Icon name="Landmark" size={12} style={{ color: t.gold }} /> An official service of the National Revenue Office
      </div>
      <header className="sticky top-0 z-10" style={{ background: t.surface, borderBottom: `3px solid ${t.primary}` }}>
        <div className="mx-auto flex max-w-6xl items-center justify-between px-6 py-3.5">
          <button onClick={() => setView("home")}><BrandLogo business={business} size={42} withWordmark /></button>
          <nav className="hidden items-center gap-1 md:flex">
            {NRO_NAV.map((n) => (
              <button key={n} onClick={() => navTo(NAV_VIEW[n])}>
                <NavItem label={n} active={VIEW_NAV[view] === n} theme={t} />
              </button>
            ))}
          </nav>
          {signedIn ? (
            <div className="flex items-center gap-2.5">
              <div className="flex items-center gap-2 rounded-lg px-2.5 py-1.5" style={{ background: t.surfaceAlt, border: `1px solid ${t.line}` }}>
                <span className="flex h-6 w-6 items-center justify-center rounded-full text-[11px] font-bold" style={{ background: t.primary, color: "#fff" }}>{NRO_USER.initials}</span>
                <span className="hidden leading-tight sm:block">
                  <span className="block text-[12.5px] font-bold" style={{ color: t.ink }}>{NRO_USER.name}</span>
                  <span className="block text-[11px]" style={{ color: t.sub }}>{NRO_USER.handle}</span>
                </span>
              </div>
              <button onClick={() => setSignedIn(false)} className="rounded-lg px-3 py-1.5 text-[13px] font-semibold" style={{ border: `1px solid ${t.line}`, color: t.primary }}>
                Sign Out
              </button>
            </div>
          ) : (
            <button onClick={() => setShowSignIn(true)} className="flex items-center gap-2 rounded-lg px-3 py-1.5 text-[13px] font-semibold" style={{ border: `1px solid ${t.line}`, color: t.primary }}>
              <Icon name="User" size={15} /> Sign In
            </button>
          )}
        </div>
      </header>

      <div className="mx-auto max-w-6xl px-6 py-6">
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-[1fr_minmax(380px,440px)]">
          <div className="space-y-5">
            {view === "home" ? (
              <>
                <NroPanel t={t}>
                  <h3 className="text-[16px] font-bold" style={{ fontFamily: t.headingFont }}>Taxpayer Services</h3>
                  <p className="mt-1 text-[13px]" style={{ color: t.sub }}>Common tasks and quick links.</p>
                  <div className="mt-4 grid grid-cols-2 gap-3">
                    {TILES.map(([ic, l, dest]) => {
                      const locked = GATED.has(dest) && !signedIn;
                      return (
                        <button key={l} onClick={() => navTo(dest)} className="flex items-center gap-2.5 rounded-lg px-3 py-3 text-left transition-all hover:-translate-y-0.5" style={{ background: t.surfaceAlt, border: `1px solid ${t.line}` }}>
                          <span className="flex h-9 w-9 items-center justify-center rounded-md" style={{ background: t.tintBubble, color: t.primary }}><Icon name={ic} size={17} /></span>
                          <span className="flex-1 text-[13px] font-semibold">{l}</span>
                          <Icon name={locked ? "Lock" : "ChevronRight"} size={14} style={{ color: t.sub }} />
                        </button>
                      );
                    })}
                  </div>
                </NroPanel>

                <NroPanel t={t}>
                  <div className="flex items-center justify-between">
                    <h3 className="text-[16px] font-bold" style={{ fontFamily: t.headingFont }}>Your account</h3>
                    {signedIn && <span className="rounded px-2 py-0.5 text-[11px] font-bold uppercase" style={{ background: t.tintBubble, color: t.accent }}>In good standing</span>}
                  </div>
                  {signedIn ? (
                    <div className="mt-3 divide-y" style={{ borderColor: t.line }}>
                      <div className="flex items-center gap-3 pb-3">
                        <span className="flex h-9 w-9 items-center justify-center rounded-full text-[13px] font-bold" style={{ background: t.primary, color: "#fff" }}>{NRO_USER.initials}</span>
                        <span className="leading-tight">
                          <span className="block text-[14px] font-bold">{NRO_USER.name}</span>
                          <span className="block text-[12px]" style={{ color: t.sub }}>Steuer-ID {NRO_USER.steuerId}</span>
                        </span>
                      </div>
                      {NRO_ACCOUNT.map(([l, v]) => (
                        <div key={l} className="flex items-center justify-between py-2.5 text-[13.5px]"><span style={{ color: t.sub }}>{l}</span><span className="font-semibold">{v}</span></div>
                      ))}
                    </div>
                  ) : (
                    <div className="mt-3 flex flex-col items-center rounded-lg py-7 text-center" style={{ background: t.surfaceAlt }}>
                      <span className="flex h-12 w-12 items-center justify-center rounded-full" style={{ background: t.tintBubble, color: t.primary }}><Icon name="Lock" size={22} /></span>
                      <p className="mt-3 text-[14px] font-semibold">Sign in to view your account</p>
                      <p className="mt-1 max-w-[16rem] text-[12.5px]" style={{ color: t.sub }}>Your tax year, refund status and balance are protected.</p>
                      <button onClick={() => setShowSignIn(true)} className="mt-3 rounded-lg px-4 py-2 text-[13px] font-bold" style={{ background: t.primary, color: "#fff" }}>Sign in</button>
                    </div>
                  )}
                </NroPanel>
              </>
            ) : (
              <div>
                <button onClick={() => setView("home")} className="mb-3 inline-flex items-center gap-1.5 text-[13px] font-semibold" style={{ color: t.primary }}>
                  <Icon name="ArrowLeft" size={15} /> Home
                </button>
                <h2 className="mb-4 text-[20px] font-bold" style={{ fontFamily: t.headingFont }}>{titleFor[view]}</h2>
                <NroTileView t={t} view={view} signedIn={signedIn} />
              </div>
            )}
          </div>

          <div style={{ height: "min(72vh, 660px)" }}>{children}</div>
        </div>
      </div>

      {showSignIn && <NroSignInForm t={t} onSignIn={handleSignIn} onClose={() => setShowSignIn(false)} />}
    </div>
  );
}

window.NroChrome = NroChrome;
