// "Make a record" — turn an email into a tracked record.
// Click → Zeranda scans the email → shows the category it thinks it is + the
// fields THAT category needs, pre-filled with what it read. You can edit every
// value by hand, and switching the category swaps the visible fields so you
// always capture the right shape of record.

// Per-category field schema. Each field: { key, label, type, opts?, icon?, placeholder?, half? }
// type: 'text' | 'amount' | 'date' | 'time' | 'select' | 'note'
const RECORD_FIELDS = {
  bill: [
    { key:'payee',   label:'Payee',     type:'text',   icon:'building-2', placeholder:'Who is billing you' },
    { key:'amount',  label:'Amount',    type:'amount', half:true },
    { key:'due',     label:'Due date',  type:'date',   half:true },
    { key:'account', label:'Pay from',  type:'select', opts:['Chase ••4821','Amex ••9007','Cash','Not set'] },
    { key:'notes',   label:'Notes',     type:'note',   placeholder:'Anything worth remembering' },
  ],
  receipt: [
    { key:'merchant', label:'Merchant', type:'text',   icon:'store', placeholder:'Where you paid' },
    { key:'amount',   label:'Amount',   type:'amount', half:true },
    { key:'date',     label:'Date',     type:'date',   half:true },
    { key:'category', label:'Spend category', type:'select', opts:['Vehicle','Groceries','Dining','Health','Travel','Home','Other'] },
    { key:'notes',    label:'Notes',    type:'note',   placeholder:'Optional' },
  ],
  package: [
    { key:'item',    label:'Item',      type:'text', icon:'package', placeholder:'What’s arriving' },
    { key:'carrier', label:'Carrier',   type:'select', opts:['Delhivery','Blue Dart','India Post','Amazon','DHL','Ekart','Other'], half:true },
    { key:'eta',     label:'Expected',  type:'date', half:true },
    { key:'tracking',label:'Tracking #',type:'text', icon:'hash', placeholder:'Tracking number' },
  ],
  event: [
    { key:'title',    label:'Title',    type:'text', icon:'calendar', placeholder:'What’s happening' },
    { key:'date',     label:'Date',     type:'date', half:true },
    { key:'time',     label:'Time',     type:'time', half:true },
    { key:'location', label:'Location', type:'text', icon:'map-pin', placeholder:'Where (or a link)' },
  ],
  task: [
    { key:'title',    label:'Task',     type:'text', icon:'check-square', placeholder:'What needs doing' },
    { key:'due',      label:'Due date', type:'date', half:true },
    { key:'priority', label:'Priority', type:'select', opts:['Low','Medium','High'], half:true },
    { key:'notes',    label:'Notes',    type:'note', placeholder:'Optional' },
  ],
  subscription: [
    { key:'service', label:'Service',   type:'text', icon:'credit-card', placeholder:'What you’re subscribed to' },
    { key:'amount',  label:'Amount',    type:'amount', half:true },
    { key:'cycle',   label:'Billing',   type:'select', opts:['Weekly','Monthly','Quarterly','Yearly'], half:true },
    { key:'next',    label:'Next charge', type:'date' },
  ],
  statement: [
    { key:'institution', label:'Institution', type:'text', icon:'landmark', placeholder:'Bank / provider' },
    { key:'account',     label:'Account',     type:'text', icon:'hash', placeholder:'Account / card', half:true },
    { key:'period',      label:'Period',      type:'text', placeholder:'e.g. June 2026', half:true },
    { key:'balance',     label:'Closing balance', type:'amount' },
  ],
};

// What Zeranda "read" from the email for a given category.
// Returns { values:{key:val}, found:{key:bool} } — found=true means AI filled it,
// found=false means it couldn't read it and you should add it by hand.
function scanEmail(m, kind) {
  const fmtDate = iso => new Date(iso).toLocaleDateString('en-US', { month:'short', day:'numeric', year:'numeric' });
  // pull a $ amount out of the suggestion detail, if any
  const amt = (() => {
    const s = (m.suggestion && m.suggestion.detail) || '';
    const mm = s.replace(/,/g,'').match(/\$\s*([\d.]+)/);
    return mm ? mm[1] : '';
  })();
  const today = fmtDate(m.dateISO);
  const name = m.from || '';
  const subj = m.subject || '';
  const V = {}, F = {};
  const set = (k, val) => { V[k] = val || ''; F[k] = !!val; };

  const fields = RECORD_FIELDS[kind] || [];
  fields.forEach(f => set(f.key, '')); // default: blank + manual

  switch (kind) {
    case 'bill':
      set('payee', name); set('amount', amt); set('due', ''); set('account', amt ? '' : ''); set('notes', '');
      F.account = false; break;
    case 'receipt':
      set('merchant', name); set('amount', amt); set('date', today);
      set('category', /motor|service|vehicle|car/i.test(name+subj) ? 'Vehicle' : ''); break;
    case 'package':
      set('item', subj.replace(/^(your |re: )/i,'')); set('carrier', ''); set('eta', ''); set('tracking', ''); break;
    case 'event':
      set('title', subj.replace(/^(hold:|invite:|re:)\s*/i,'')); set('date', ''); set('time', ''); set('location', ''); break;
    case 'task':
      set('title', subj); set('due', ''); set('priority', 'Medium'); break;
    case 'subscription':
      set('service', name); set('amount', amt); set('cycle', 'Monthly'); set('next', ''); break;
    case 'statement':
      set('institution', name); set('account', ''); set('period', new Date(m.dateISO).toLocaleDateString('en-US',{month:'long',year:'numeric'})); set('balance', amt); break;
    default: break;
  }
  return { values: V, found: F };
}

function RecordModal({ m, onClose, onSave }) {
  const startKind = (m.suggestion && m.suggestion.kind) || (m.outcome && m.outcome.kind) || 'bill';
  const [phase, setPhase] = useState('scan');        // 'scan' → 'form'
  const [kind, setKind] = useState(startKind);
  const [vals, setVals] = useState({});
  const [found, setFound] = useState({});

  // initial scan
  useEffect(() => {
    const r = scanEmail(m, startKind);
    const t = setTimeout(() => { setVals(r.values); setFound(r.found); setPhase('form'); }, 1250);
    return () => clearTimeout(t);
  }, []);

  // re-scan when the category is changed by hand — gives the right fields + a fresh read
  const changeKind = k => {
    if (k === kind) return;
    const r = scanEmail(m, k);
    setKind(k);
    setVals(r.values);
    setFound(r.found);
  };

  const setVal = (key, v) => { setVals(p => ({ ...p, [key]: v })); setFound(p => ({ ...p, [key]: true })); };

  const fields = RECORD_FIELDS[kind] || [];
  const K = MAIL_KIND[kind];
  const kindOpts = Object.keys(MAIL_KIND).map(k => ({ value:k, label: MAIL_KIND[k].verb, icon: MAIL_KIND[k].icon, tint: MAIL_KIND[k].tint }));
  const readCount = fields.filter(f => found[f.key]).length;

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal rec-modal zd-scroll" onClick={e => e.stopPropagation()}>
        <button className="modal-x" onClick={onClose} aria-label="Close"><Icon name="x" size={18} /></button>

        {phase === 'scan' ? (
          <div className="rec-scan">
            <span className="rec-scan-orb"><Icon name="sparkles" size={26} color="var(--gold-700)" /></span>
            <div className="rec-scan-t">Pulling out the details…</div>
            <div className="rec-scan-s">Zeranda is pulling out the details worth keeping.</div>
            <div className="rec-scan-lines">
              <span style={{ width:'92%' }} /><span style={{ width:'78%' }} /><span style={{ width:'85%' }} /><span style={{ width:'60%' }} />
            </div>
          </div>
        ) : (
          <React.Fragment>
            <div className="modal-body">
              <span className="modal-badge rec-badge"><Icon name="sparkles" size={13} color="var(--gold-700)" /> New record</span>
              <h3>Make a record from this email</h3>
              <div className="msub">
                Zeranda read <b>{m.from}</b> — “{m.subject}”. {readCount > 0
                  ? <React.Fragment>It filled in {readCount} {readCount === 1 ? 'field' : 'fields'} — check them and add anything it missed.</React.Fragment>
                  : <React.Fragment>Add the details below.</React.Fragment>}
              </div>

              {/* Category — drives which fields you see */}
              <div className="fl">
                <label className="fl-k">Record type <span className="opt">— change this to switch the fields</span></label>
                <Dropdown value={kind} options={kindOpts} icon={K.icon} minWidth={220} onChange={changeKind} />
              </div>

              <div className="rec-sep"><span style={{ background: tintBg(K.tint), color: tintFg(K.tint) }}><Icon name={K.icon} size={13} color={tintFg(K.tint)} /> {K.verb} details</span></div>

              {/* Fields for the chosen category */}
              <div className="rec-grid">
                {fields.map(f => (
                  <div className={`fl rec-fl ${f.half ? 'half' : ''}`} key={f.key}>
                    <label className="fl-k">
                      {f.label}
                      {found[f.key]
                        ? <span className="rec-tag read"><Icon name="sparkles" size={10} color="var(--gold-700)" /> read</span>
                        : <span className="rec-tag manual">add manually</span>}
                    </label>
                    <RecordField f={f} value={vals[f.key] || ''} onChange={v => setVal(f.key, v)} />
                  </div>
                ))}
              </div>
            </div>

            <div className="modal-foot">
              <button className="btn btn-ghost" onClick={onClose}>Cancel</button>
              <button className="btn btn-primary" onClick={() => onSave(m, kind, vals)}>
                <Icon name="check" size={15} /> Create {K.verb.toLowerCase()}
              </button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

// A single field, rendered by type.
function RecordField({ f, value, onChange }) {
  if (f.type === 'select') {
    const opts = f.opts.map(o => ({ value:o, label:o }));
    return <Dropdown value={value} options={opts} placeholder="Choose…" minWidth={160} onChange={onChange} />;
  }
  if (f.type === 'amount') {
    return (
      <div className="rec-amount">
        <span className="rec-cur">$</span>
        <input inputMode="decimal" placeholder="0" value={value} onChange={e => onChange(e.target.value)} />
      </div>
    );
  }
  if (f.type === 'date' || f.type === 'time') {
    return (
      <div className="rec-iconinput">
        <Icon name={f.type === 'date' ? 'calendar' : 'clock'} size={15} color="var(--fg-3)" />
        <input placeholder={f.type === 'date' ? 'e.g. Jun 28, 2026' : 'e.g. 4:30 PM'} value={value} onChange={e => onChange(e.target.value)} />
      </div>
    );
  }
  if (f.type === 'note') {
    return <textarea className="fld" placeholder={f.placeholder} value={value} onChange={e => onChange(e.target.value)} />;
  }
  // text
  return (
    <div className="rec-iconinput">
      {f.icon && <Icon name={f.icon} size={15} color="var(--fg-3)" />}
      <input placeholder={f.placeholder} value={value} onChange={e => onChange(e.target.value)} />
    </div>
  );
}

window.RecordModal = RecordModal;
