/* Features catalog — every feature, tagged with Basic / Pro / Free.
   Used on features.html. */

const TIER_META = {
  free:  { label: 'Free',  cls: 'free'  },
  basic: { label: 'Basic', cls: 'basic' },
  pro:   { label: 'Pro',   cls: 'pro'   },
};

const TierBadge = ({tier}) => {
  const m = TIER_META[tier];
  return <span className={`tier-badge ${m.cls}`}>{m.label}</span>;
};

/* Each entry: name, body, tier, optional secondary tier (e.g. "basic with limits, full on pro") */
const FEATURE_CATALOG = [
  {
    id: 'calculator',
    title: 'Calculator',
    accent: 'var(--sa-accent-hi)',
    iconBg: 'var(--sa-accent-dim)',
    iconBd: 'var(--sa-accent-bd)',
    icon: 'Calculator',
    items: [
      { name: 'ACCP recommended rates',
        body: 'Every department, every position — Camera, Sound, Grip, Electric, Wardrobe, Locations, ADs, more. Built from the latest July 2025 → June 2026 rate card.',
        tier: 'free', notes: 'Free is limited; Basic unlocks all roles.' },
      { name: 'Custom roles & flat day rates',
        body: 'Build your own role, your own rate, your own OT scale. Save it and reuse it on every job.',
        tier: 'basic' },
      { name: 'Overtime 1.5× / 2× / 3× scales',
        body: 'OT 1.5× hours 1–2, OT 2× hours 3–4, OT 3× hour 5+ — calculated automatically as you punch in your hours.',
        tier: 'free' },
      { name: 'Meal penalties, kit fees, multipliers',
        body: 'Pre-call bumps, weekend bumps, holiday rates, mileage adders. Set it once, it lives on every calc.',
        tier: 'basic' },
      { name: 'Save & re-open calculations',
        body: 'Save a calc to a job, share it with a PM, paste it into an invoice. Three saves on Free, unlimited on Basic and up.',
        tier: 'basic' },
      { name: 'Per-day breakdown export',
        body: 'PDF or share-sheet a clean breakdown of a day rate — base, OT, penalties, kit — for sending to production.',
        tier: 'basic' },
    ],
  },
  {
    id: 'invoicing',
    title: 'Invoicing',
    accent: 'var(--sa-green)',
    iconBg: 'rgba(48,209,88,0.10)',
    iconBd: 'rgba(48,209,88,0.30)',
    icon: 'Invoice',
    items: [
      { name: 'Email invoices to clients',
        body: 'Gear-only, labour-only, or combined. Auto-numbered. Net 15 / 30 / 60. Tax per line. PDF attached.',
        tier: 'basic' },
      { name: 'Production company address book',
        body: 'Remembers who you bill, what they owe, and what you usually charge them. New invoice in three taps.',
        tier: 'basic' },
      { name: 'Branded PDFs with your logo',
        body: 'Drop your logo once. Every PDF that goes to a client carries it — header, footer, payment block.',
        tier: 'pro' },
      { name: 'Auto invoice numbering & history',
        body: 'Sequential numbering, no gaps. Search by client, status, year. Every invoice you\'ve ever sent, one tap away.',
        tier: 'basic' },
      { name: 'Status tracking — sent / paid / overdue',
        body: 'Mark paid as cheques clear. Overdue invoices float to the top so nothing slips.',
        tier: 'basic' },
    ],
  },
  {
    id: 'crew',
    title: 'Crew & Calendar',
    accent: 'var(--sa-pink)',
    iconBg: 'rgba(255,55,95,0.10)',
    iconBd: 'rgba(255,55,95,0.30)',
    icon: 'Crew',
    items: [
      { name: 'Calendar — book your shoot days',
        body: 'Block shoot days, holds, wraps. See your month at a glance. Stop double-booking by accident.',
        tier: 'basic' },
      { name: 'Crew directory profile',
        body: 'Role, location, kit, availability. PMs in the directory can find you and reach out.',
        tier: 'basic' },
      { name: 'Teams — split rentals',
        body: 'Three of you sharing a truck rental? Split the cost three ways with a tap.',
        tier: 'basic' },
      { name: 'Sun tracker & call sheet times',
        body: 'Accurate sunrise, sunset, magic hour for any location on your call sheet.',
        tier: 'basic' },
      { name: 'Discover & book crew (PM)',
        body: 'Production Manager view: browse the directory, filter by role and location, message and book.',
        tier: 'pro' },
      { name: 'Claim a Job & My Jobs (PM)',
        body: 'Claim ownership of a production, invite crew, track who\'s confirmed.',
        tier: 'pro' },
    ],
  },
  {
    id: 'mileage',
    title: 'Mileage',
    accent: 'var(--sa-green)',
    iconBg: 'rgba(48,209,88,0.10)',
    iconBd: 'rgba(48,209,88,0.30)',
    icon: 'Car',
    items: [
      { name: 'Automatic drive detection',
        body: 'Set Assist watches in the background and starts a drive the moment you pull off the lot — no app to open, no button to press.',
        tier: 'pro' },
      { name: 'CRA-correct math, automatic',
        body: '$0.70/km for the first 5,000, $0.64/km after. Your year-to-date deduction updates on every trip.',
        tier: 'pro' },
      { name: 'Per-trip route + edit',
        body: 'See every leg on a map. Merge, split, or delete a drive. Add a purpose so the CRA knows what it was for.',
        tier: 'pro' },
      { name: 'Auto-categorize to a job',
        body: 'Drives land against the right production, so when you wrap a job your mileage rolls into its P&L.',
        tier: 'pro' },
    ],
  },
  {
    id: 'receipts',
    title: 'Receipts',
    accent: 'var(--sa-teal)',
    iconBg: 'rgba(64,200,224,0.10)',
    iconBd: 'rgba(64,200,224,0.30)',
    icon: 'Receipt',
    items: [
      { name: 'Camera scanning',
        body: 'Point the camera at a receipt and Set Assist reads vendor, date, subtotal, HST, total — and files it.',
        tier: 'pro' },
      { name: 'PDF & photo import',
        body: 'Drop in a screenshot, an email PDF, or a photo from your library. Same OCR, same auto-fill.',
        tier: 'pro' },
      { name: 'Auto-categorize against a job',
        body: 'Every expense lands in the right category against the right production. No typing, no shoebox.',
        tier: 'pro' },
      { name: 'HST extraction',
        body: 'Tax is pulled out and stored separately so your quarterly remittance stays accurate.',
        tier: 'pro' },
      { name: 'Searchable archive',
        body: 'Find any receipt by vendor, job, date, or amount. Photo attached so your accountant has the original.',
        tier: 'pro' },
    ],
  },
  {
    id: 'finances',
    title: 'Finances',
    accent: 'var(--sa-amber)',
    iconBg: 'rgba(255,159,10,0.10)',
    iconBd: 'rgba(255,159,10,0.30)',
    icon: 'Finances',
    items: [
      { name: 'Year-to-date dashboard',
        body: 'Every invoice, expense, and drive lands in one dashboard. Income, expenses, net — at a glance.',
        tier: 'pro' },
      { name: 'HST quarterly tracking',
        body: 'HST tracked by quarter so you stop being surprised in July. Auto-rolled from every invoice and receipt.',
        tier: 'pro' },
      { name: 'Expenses by category',
        body: 'Equipment, vehicle, meals, supplies, professional fees — CRA-friendly buckets, no setup required.',
        tier: 'pro' },
      { name: 'P&L at a glance',
        body: 'Profit and loss by month, by quarter, by year. See where the money actually went.',
        tier: 'pro' },
      { name: 'T2125-ready Excel export',
        body: 'Five-sheet workbook: invoices, expenses, mileage, monthly summary, P&L — built the way the CRA wants to see it.',
        tier: 'pro' },
    ],
  },
  {
    id: 'ad-tools',
    title: 'AD Tools',
    accent: 'var(--sa-pink)',
    iconBg: 'rgba(255,55,95,0.10)',
    iconBd: 'rgba(255,55,95,0.30)',
    icon: 'Stopwatch',
    items: [
      { name: 'Child performer Live Activity timer',
        body: 'Daily-hour limits for child performers as a Lock Screen Live Activity — visible in the Dynamic Island, even with Set Assist closed.',
        tier: 'pro' },
      { name: 'Age-bracket presets',
        body: 'ACCP daily limits per age bracket built in. Pick the kid, pick the bracket, tap start.',
        tier: 'pro' },
      { name: 'Five-minute warning alert',
        body: 'A five-minute warning before the limit so you have time to wrap — without staring at a clock.',
        tier: 'pro' },
      { name: 'Multi-performer tracking',
        body: 'Track every minor on the call sheet side-by-side, each with their own countdown.',
        tier: 'pro' },
    ],
  },
  {
    id: 'payroll',
    title: 'Payroll Wrap',
    accent: 'var(--sa-purple)',
    iconBg: 'rgba(191,90,242,0.12)',
    iconBd: 'rgba(191,90,242,0.35)',
    icon: 'Payroll',
    items: [
      { name: 'Per-crew timesheets',
        body: 'Add the crew, pull their timesheets, edit per-day rates without breaking totals.',
        tier: 'pro' },
      { name: 'ACCP line-number assignment',
        body: 'Common-line presets handle 80% of jobs. Override per crew if your production codes the budget differently.',
        tier: 'pro' },
      { name: 'Payroll-ready export bundle',
        body: 'PDF or CSV your favourite payroll service can import. One file, one click, ready to wire.',
        tier: 'pro' },
      { name: 'Wrap summary by production',
        body: 'Total payroll, totals by line, totals by department. The wrap-day number every PM needs.',
        tier: 'pro' },
    ],
  },
  {
    id: 'kit',
    title: 'Kit Inventory',
    accent: 'var(--sa-teal)',
    iconBg: 'rgba(64,200,224,0.10)',
    iconBd: 'rgba(64,200,224,0.30)',
    icon: 'Kit',
    items: [
      { name: 'Track every item',
        body: 'Body, lens, monitor, stand, magliner — log it once with a daily rate and value.',
        tier: 'pro' },
      { name: 'Drop into calc & invoices',
        body: 'When a job calls for kit, pull items into a calc or invoice — rates auto-fill.',
        tier: 'pro' },
      { name: 'Insurance manifest export',
        body: 'Export a manifest with serial numbers and replacement values for insurance renewals.',
        tier: 'pro' },
      { name: 'Retire / sold tracking',
        body: 'Mark items sold, lost, or retired. Your kit value stays accurate as your gear changes.',
        tier: 'pro' },
    ],
  },
  {
    id: 'account',
    title: 'Account & Sync',
    accent: 'var(--sa-accent-hi)',
    iconBg: 'var(--sa-accent-dim)',
    iconBd: 'var(--sa-accent-bd)',
    icon: 'Calendar',
    items: [
      { name: 'Sign in with Apple or email',
        body: 'One tap with Apple ID, or use email and a password. No phone number required.',
        tier: 'free' },
      { name: 'Cross-device sync',
        body: 'Phone in your pocket, iPad on the truck — your data is the same on both.',
        tier: 'basic' },
      { name: 'Offline-first',
        body: 'Log a meal penalty in a parking garage. Your changes sync the moment you have signal again.',
        tier: 'free' },
      { name: 'Priority email support',
        body: 'Pro subscribers get a dedicated inbox. Real humans, on-set hours.',
        tier: 'pro' },
    ],
  },
];

/* Count features per tier — for the filter chip counts.
   "free" features are also implicitly available on Basic and Pro;
   "basic" features are also available on Pro. The counts reflect that. */
function countByTier() {
  const c = { all: 0, free: 0, basic: 0, pro: 0 };
  FEATURE_CATALOG.forEach(g => g.items.forEach(it => {
    c.all++;
    if (it.tier === 'free')  { c.free++; c.basic++; c.pro++; }
    if (it.tier === 'basic') { c.basic++; c.pro++; }
    if (it.tier === 'pro')   { c.pro++; }
  }));
  return c;
}

/* Which icon component to render (by name) */
const IconByName = ({name, color}) => {
  const map = { Calculator, Invoice, Crew, Finances, Payroll, Kit, Calendar, Car, Receipt, Stopwatch };
  const C = map[name] || Calculator;
  return <C size={18} color={color}/>;
};

/* "Tier matches filter?" – includes the implicit hierarchy. */
function matchesFilter(itemTier, filter) {
  if (filter === 'all') return true;
  if (filter === 'free')  return itemTier === 'free';
  if (filter === 'basic') return itemTier === 'free' || itemTier === 'basic';
  if (filter === 'pro')   return true;
  return true;
}

const FeaturesCatalog = () => {
  const [filter, setFilter] = React.useState('all');
  const counts = React.useMemo(countByTier, []);

  return (
    <section className="section" style={{paddingTop: 20, paddingBottom: 60}}>
      <div className="container">
        {/* Filter bar */}
        <div className="reveal in" style={{
          display:'flex', justifyContent:'center', gap:8, flexWrap:'wrap',
          marginBottom: 48,
        }}>
          {[
            {id:'all',   label:'All'},
            {id:'free',  label:'Free'},
            {id:'basic', label:'Basic'},
            {id:'pro',   label:'Pro'},
          ].map(f => (
            <button
              key={f.id}
              className={`filter-pill ${filter===f.id ? 'active' : ''}`}
              onClick={()=>setFilter(f.id)}
            >
              {f.label}
              <span className="count">{counts[f.id]}</span>
            </button>
          ))}
        </div>

        {/* Categories */}
        {FEATURE_CATALOG.map((group, gi) => {
          const visible = group.items.filter(it => matchesFilter(it.tier, filter));
          if (visible.length === 0) return null;
          return (
            <div key={group.id} className="reveal" data-stagger={Math.min(gi,7)} style={{marginBottom: 72}}>
              <div className="cat-head">
                <span className="cat-num">{String(gi+1).padStart(2,'0')}</span>
                <div style={{
                  width:36, height:36, borderRadius:9,
                  display:'grid', placeItems:'center',
                  background: group.iconBg,
                  border: `0.5px solid ${group.iconBd}`,
                }}>
                  <IconByName name={group.icon} color={group.accent}/>
                </div>
                <h2 className="display" style={{fontSize:'clamp(26px, 3.4vw, 38px)', margin:0, letterSpacing:'-0.025em'}}>
                  {group.title}
                </h2>
                <div className="cat-rule"/>
                <span style={{fontSize:12, color:'var(--sa-text4)', fontVariantNumeric:'tabular-nums', whiteSpace:'nowrap'}}>
                  {visible.length} {visible.length===1?'feature':'features'}
                </span>
              </div>

              <div className="catalog-grid">
                {visible.map((it, i) => (
                  <div
                    key={i}
                    className="feature-card reveal"
                    data-stagger={Math.min(i,7)}
                    style={{
                      '--card-glow': `${group.accent.replace(')', ', 0.12)').replace('rgb', 'rgba').replace('var(', 'var(')}`,
                      '--card-icon-bg': group.iconBg,
                      '--card-icon-bd': group.iconBd,
                    }}
                  >
                    <div className="fc-head">
                      <div className="fc-icon">
                        <IconByName name={group.icon} color={group.accent}/>
                      </div>
                      <TierBadge tier={it.tier}/>
                    </div>
                    <div className="fc-title">{it.name}</div>
                    <div className="fc-body">{it.body}</div>
                    {it.notes && (
                      <div style={{
                        marginTop: 10, fontSize: 11, color:'var(--sa-text4)',
                        letterSpacing:'-0.01em', fontStyle:'italic',
                      }}>{it.notes}</div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      <style>{`
        .catalog-grid {
          display: grid;
          grid-template-columns: repeat(3, minmax(0, 1fr));
          gap: 14px;
        }
        @media (max-width: 980px) {
          .catalog-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
        }
        @media (max-width: 620px) {
          .catalog-grid { grid-template-columns: 1fr; }
        }
      `}</style>
    </section>
  );
};

Object.assign(window, { FeaturesCatalog, FEATURE_CATALOG, TierBadge });
