/* ============================================================
   P&L App (Lite) · paid-plan features, shown LOCKED (Ana, 17 Nov 2026)
   ------------------------------------------------------------
   Lite is free. The paid plan's features stay visible, blurred, with a lock; a click opens
   one small card: "This is part of the paid plan", what it does, and Book a call.

   Rules (briefs/65-lite-feature-list.md):
   - What sits under a blur is MADE-UP sample content written in this file, never the client's
     own data. (Lite does not even store jobs, vehicles or part payments.)
   - In the add / edit forms the paid fields are not blurred one by one: one locked strip.
   - Trade-only features carry `trade: true`. Version 1 is trades only, so they all show.
     When Lite gets a non-trade client, an industry setting per company decides SHOW_TRADE.
   ============================================================ */
const BOOK_CALL_URL = 'https://calendly.com/retiply/30min';
function showTrade() { return true; }   // later: DB.company.industry === 'trades'

/* Every locked feature, in one place: what the card says about it. */
const PAID_FEATURES = {
  import:     { title: 'Automatic import', what: 'Send a PDF, a photo of a receipt or a bank CSV and the rows fill themselves in. No typing.' },
  quickbooks: { title: 'Connect QuickBooks', what: 'Your QuickBooks books read every night, so this app is always up to date without typing anything twice.' },
  document:   { title: 'The document on every row', what: 'The invoice or receipt is kept with its row, one click away, for you and your accountant.' },
  parts:      { title: 'Part payments', what: 'Record an invoice paid in pieces and always see what is still owed.' },
  split:      { title: 'Split a bill', what: 'Share one bill across several categories (materials and tools on the same receipt).' },
  team:       { title: 'Logins for your team', what: 'Give your bookkeeper, partner or office manager their own login to the same books. The free plan has one login per company.' },
  fields:     { title: 'More detail on every row', what: 'Payment method, date paid, who approved it, and more, on every row and in every filter.' },
  jobs:       { title: 'Jobs', trade: true, what: 'Profit on every job: what it billed, what it cost, its share of the overheads, what is still to bill.' },
  pnlJobs:    { title: 'Profit by job', trade: true, what: 'Which jobs make money and which do not, with the overheads shared out fairly.' },
  vehicles:   { title: 'Vehicles', trade: true, what: 'Fuel and repairs per truck, month by month.' },
  retainage:  { title: 'Retainage', trade: true, what: 'What customers are holding back until a job is finished, and when it is due.' },
};

/* The card. Any locked thing calls openPaid('jobs'). */
function openPaid(key) { window.dispatchEvent(new CustomEvent('show-paid', { detail: key })); }

function PaidCard() {
  const [key, setKey] = useState(null);
  useEffect(() => {
    const on = e => setKey(e.detail);
    window.addEventListener('show-paid', on);
    return () => window.removeEventListener('show-paid', on);
  }, []);
  const f = key && PAID_FEATURES[key];
  return (
    <Modal open={!!f} onClose={() => setKey(null)} width={460} icon="lock" title={f ? f.title : ''}
      subtitle="This is part of the paid plan"
      footer={<>
        <Button variant="ghost" onClick={() => setKey(null)}>Not now</Button>
        <a href={BOOK_CALL_URL} target="_blank" rel="noopener" onClick={() => setKey(null)}
           className="inline-flex items-center gap-2 h-10 px-4 rounded-xl text-[13.5px] font-700"
           style={{ background: 'var(--lime)', color: 'var(--sidebar)' }}>
          <Icon name="calendar" size={16} />Book a call
        </a>
      </>}>
      {f && (
        <div className="flex flex-col gap-3">
          <p className="text-[14px] text-ink leading-relaxed">{f.what}</p>
          <p className="text-[12.5px] text-muted leading-relaxed">The paid plan adds this and the automatic import to the app you already use: same login, same numbers. Book a 30-minute call and we'll show you.</p>
        </div>
      )}
    </Modal>
  );
}

/* A small lock, the same everywhere. */
function LockMark({ size = 13, className = '' }) {
  return <span className={'inline-flex items-center justify-center shrink-0 ' + className} style={{ color: '#9AA298' }}><Icon name="lock" size={size} /></span>;
}

/* A button that stays where the real one was, with a lock. */
function LockedButton({ feature, icon, children, size }) {
  return (
    <Button variant="outline" size={size} icon={icon} onClick={() => openPaid(feature)} title="Part of the paid plan">
      <span className="inline-flex items-center gap-1.5">{children}<LockMark size={12} /></span>
    </Button>
  );
}

/* The strip at the bottom of an add / edit form: the paid fields, named, one click to the card. */
function LockedStrip({ items }) {
  return (
    <button type="button" onClick={() => openPaid('fields')}
      className="w-full flex items-start gap-3 px-4 py-3 rounded-xl text-left border border-dashed border-line hover:bg-[#F6F8F3] transition-colors">
      <LockMark size={15} className="mt-0.5" />
      <span className="min-w-0">
        <span className="block text-[12.5px] font-700 text-ink">More fields on the paid plan</span>
        <span className="block text-[12px] text-muted">{items.join(', ')}</span>
      </span>
    </button>
  );
}

/* A blurred block with the lock on top. `children` = the made-up sample content. */
function LockedBlock({ feature, children, className = '', minH }) {
  const f = PAID_FEATURES[feature];
  if (f && f.trade && !showTrade()) return null;
  return (
    <div className={'relative overflow-hidden rounded-2xl ' + className} style={minH ? { minHeight: minH } : undefined}>
      <div aria-hidden="true" className="pointer-events-none select-none" style={{ filter: 'blur(5px)', opacity: 0.75 }}>{children}</div>
      <button type="button" onClick={() => openPaid(feature)} className="absolute inset-0 flex items-center justify-center p-4" style={{ background: 'rgba(242,244,239,0.35)' }}>
        <span className="flex flex-col items-center text-center gap-2 max-w-[340px] px-6 py-5 rounded-2xl bg-surface shadow-pop border border-line">
          <span className="inline-flex items-center justify-center w-10 h-10 rounded-xl" style={{ background: 'var(--lime)', color: 'var(--sidebar)' }}><Icon name="lock" size={19} /></span>
          <span className="text-[15px] font-800 text-ink">{f ? f.title : 'Paid plan'}</span>
          <span className="text-[12.5px] text-muted leading-relaxed">{f ? f.what : ''}</span>
          <span className="text-[12.5px] font-700 mt-1" style={{ color: 'var(--primary)' }}>Part of the paid plan · see how</span>
        </span>
      </button>
    </div>
  );
}

/* ---------- the made-up sample content under the blurs ---------- */
const _SAMPLE_JOBS = [
  ['Westchase kitchen remodel', 48200, 31400], ['Katy ISD gym floor', 36500, 29800], ['Heights bungalow addition', 61750, 43900],
  ['Memorial office fit-out', 22400, 15100], ['Pearland roof repair', 9800, 7650],
];
function _SampleTable({ head, rows }) {
  return (
    <table className="w-full border-collapse">
      <thead><tr className="text-[11.5px] uppercase tracking-wide text-muted">{head.map((h, i) => <th key={i} className={'font-600 pb-3 ' + (i ? 'text-right' : 'text-left pl-2')}>{h}</th>)}</tr></thead>
      <tbody>{rows.map((r, i) => (
        <tr key={i} className="border-t border-line">{r.map((c, j) => <td key={j} className={'py-3 text-[13px] ' + (j ? 'text-right num' : 'pl-2 text-ink font-medium')}>{c}</td>)}</tr>
      ))}</tbody>
    </table>
  );
}
function _jobRows() {
  return _SAMPLE_JOBS.map(([n, b, c]) => [n, money0USD(b), money0USD(c), money0USD(b - c), pct((b - c) / b * 100)]);
}

/* P&L: the "Profit by job" card. */
function LockedProfitByJob({ className = '' }) {
  return (
    <LockedBlock feature="pnlJobs" className={className}>
      <Card className="p-6">
        <h3 className="text-[15.5px] font-700 text-ink font-display">Profit by job</h3>
        <p className="text-[12.5px] text-muted mt-0.5 mb-4">Overheads shared by each job's share of the costs, worked out each month.</p>
        <_SampleTable head={['Job', 'Income', 'Costs', 'Profit', 'Margin']} rows={_jobRows()} />
      </Card>
    </LockedBlock>
  );
}

/* The Jobs tab. */
function LockedJobs() {
  return (
    <LockedBlock feature="jobs" minH={560}>
      <div className="flex flex-col gap-4">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          {[['Billed this year', '$178,650'], ['Still to bill', '$64,300'], ['Retainage held', '$12,840']].map(([l, v]) => (
            <Card key={l} className="px-6 py-5"><div className="text-[13px] font-700 text-muted">{l}</div><div className="text-[30px] font-800 num mt-2">{v}</div></Card>
          ))}
        </div>
        <Card className="p-6"><_SampleTable head={['Job', 'Billed', 'Costs', 'Profit', 'Margin']} rows={_jobRows()} /></Card>
      </div>
    </LockedBlock>
  );
}

/* The Vehicles tab. */
function LockedVehicles() {
  const trucks = [['RXT-4821 · Ford F-250', 1840, 620], ['KTY-1190 · Ram 2500', 1525, 1180], ['HTX-7702 · Silverado', 1310, 240], ['BLR-3356 · Transit van', 980, 410]];
  return (
    <LockedBlock feature="vehicles" minH={520}>
      <div className="flex flex-col gap-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {[['Fuel this year', '$5,655'], ['Repairs this year', '$2,450']].map(([l, v]) => (
            <Card key={l} className="px-6 py-5"><div className="text-[13px] font-700 text-muted">{l}</div><div className="text-[30px] font-800 num mt-2">{v}</div></Card>
          ))}
        </div>
        <Card className="p-6"><_SampleTable head={['Truck', 'Fuel', 'Repairs', 'Total']} rows={trucks.map(([n, f, r]) => [n, money0USD(f), money0USD(r), money0USD(f + r)])} /></Card>
      </div>
    </LockedBlock>
  );
}

/* One row of locked fields inside the open-a-row card (document, part payments, the paid fields). */
function LockedLine({ feature, label }) {
  return (
    <button type="button" onClick={() => openPaid(feature)} className="w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left border border-dashed border-line hover:bg-[#F6F8F3] transition-colors">
      <LockMark size={15} />
      <span className="flex-1 text-[12.5px] text-ink font-600">{label}</span>
      <span className="text-[12px]" style={{ color: 'var(--primary)' }}>Paid plan</span>
    </button>
  );
}

Object.assign(window, {
  BOOK_CALL_URL, PAID_FEATURES, showTrade, openPaid, PaidCard, LockMark, LockedButton, LockedStrip, LockedBlock, LockedLine,
  LockedProfitByJob, LockedJobs, LockedVehicles,
});
