// Vendors — mobile screen, store-backed, full CRUD via FormSheet.

const VENDOR_ROLES = [
  { value: 'Venue',         label: 'Venue'         },
  { value: 'Florist',       label: 'Florist'       },
  { value: 'Caterer',       label: 'Caterer'       },
  { value: 'Photographer',  label: 'Photography'   },
  { value: 'Music',         label: 'Music · DJ'    },
  { value: 'Cake',          label: 'Cake'          },
  { value: 'Attire',        label: 'Attire'        },
  { value: 'Stationery',    label: 'Stationery'    },
  { value: 'Transport',     label: 'Transport'     },
  { value: 'Hair & Makeup', label: 'Hair & makeup' },
  { value: 'Officiant',     label: 'Officiant'     },
  { value: 'Other',         label: 'Other'         },
];

const VENDOR_STATUS = [
  { value: 'researching', label: 'Researching' },
  { value: 'booked',      label: 'Booked',  color: '#a87a4f' },
  { value: 'partial',     label: 'Partial', color: '#a87a4f' },
  { value: 'due',         label: 'Due',     color: '#c98a3a' },
  { value: 'paid',        label: 'Paid',    color: '#6f8a6a' },
];

function vendorFields() {
  return [
    { name: 'name',    label: 'Vendor name', type: 'text',
      placeholder: 'e.g. Bloom & Field Florals' },
    { name: 'role',    label: 'Role',        type: 'choice',
      options: VENDOR_ROLES },
    { name: 'contact', label: 'Contact',     type: 'text',
      placeholder: 'Name or phone or email' },
    { name: 'status',  label: 'Status',      type: 'choice', default: 'researching',
      options: VENDOR_STATUS },
    { name: 'total',   label: 'Contract total', type: 'number',
      min: 0, max: 200000, step: 100, default: 0, unit: '$' },
    { name: 'paid',    label: 'Paid so far',    type: 'number',
      min: 0, max: 200000, step: 100, default: 0, unit: '$' },
    { name: 'next',    label: 'Next milestone', type: 'text',
      placeholder: 'e.g. Final payment Sep 8' },
    { name: 'notes',   label: 'Notes',         type: 'textarea',
      placeholder: 'Anything to remember' },
  ];
}

function VendorsScreen({ onBack }) {
  const vendors = useVendors();
  const [filter, setFilter] = React.useState('all');
  const [editing, setEditing] = React.useState(null);

  const all = vendors.all;
  const filtered = all.filter(v =>
    filter === 'all' ? true :
    filter === 'attention' ? v.status === 'due' :
    v.status === filter
  );
  const isEmpty = all.length === 0;

  const submitVendor = (values) => {
    const norm = {
      ...values,
      paid:  Number(values.paid)  || 0,
      total: Number(values.total) || 0,
    };
    if (editing === 'new') vendors.addVendor(norm);
    else vendors.updateVendor(editing.id, norm);
    setEditing(null);
  };

  const deleteCurrent = () => {
    if (editing && editing !== 'new') {
      vendors.deleteVendor(editing.id);
      setEditing(null);
    }
  };

  return (
    <div style={{ background: W.bg, paddingBottom: 28, position: 'relative' }}>
      <div style={{ paddingTop: 56 }}/>

      {/* Back row */}
      {onBack && (
        <div style={{
          padding: '4px 16px 4px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <button onClick={onBack} style={{
            background: W.card, border: `0.5px solid ${W.line}`,
            width: 36, height: 36, borderRadius: 999, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
          }}>
            <Icon name="chevronL" size={14} color={W.ink2}/>
          </button>
          <button onClick={() => setEditing('new')} style={{
            width: 36, height: 36, borderRadius: 999,
            background: W.card, border: `0.5px solid ${W.line}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer', padding: 0,
          }}>
            <Icon name="plus" size={16} color={W.ink2}/>
          </button>
        </div>
      )}

      <div style={{ padding: '14px 22px 18px' }}>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
          letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
        }}>Vendors</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 34, fontWeight: 500,
          color: W.ink, letterSpacing: -0.6, lineHeight: 1, marginTop: 4,
        }}>{all.length === 0
              ? 'Your team'
              : `${all.length} ${all.length === 1 ? 'on the team' : 'on the team'}`}</div>
      </div>

      {isEmpty ? (
        <EmptyVendors onAdd={() => setEditing('new')}/>
      ) : (
        <>
          {/* Hero stats card */}
          <div style={{ padding: '0 16px 16px' }}>
            <Card style={{ padding: 22 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                    letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
                  }}>Paid to date</div>
                  <div style={{
                    fontFamily: FONT_DISPLAY, fontSize: 32, color: W.ink,
                    letterSpacing: -0.6, lineHeight: 1, marginTop: 6,
                  }}>{fmt$(vendors.paidToDate)}</div>
                </div>
                <div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                    letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
                  }}>Still owed</div>
                  <div style={{
                    fontFamily: FONT_DISPLAY, fontSize: 32, color: W.ink,
                    letterSpacing: -0.6, lineHeight: 1, marginTop: 6,
                  }}>{fmt$(vendors.owed)}</div>
                </div>
              </div>
              <div style={{
                marginTop: 18, paddingTop: 18, borderTop: `0.5px solid ${W.lineSoft}`,
                display: 'flex', gap: 14,
              }}>
                <VStat n={vendors.bookedCount}        label="Booked"      color={W.sage}/>
                <VStat n={vendors.counts.paid}        label="Paid"        color={W.clay}/>
                <VStat n={vendors.counts.researching} label="Researching" color={W.faint}/>
              </div>
            </Card>
          </div>

          {/* Filter chips */}
          <div style={{ display: 'flex', gap: 8, padding: '0 22px 14px', overflowX: 'auto' }}>
            {[
              ['all',         'All',          all.length],
              ['attention',   'Due',          vendors.counts.due],
              ['booked',      'Booked',       vendors.counts.booked],
              ['partial',     'Partial',      vendors.counts.partial],
              ['paid',        'Paid',         vendors.counts.paid],
              ['researching', 'Researching',  vendors.counts.researching],
            ].map(([k, label, n]) => {
              const active = filter === k;
              return (
                <button key={k} onClick={() => setFilter(k)} style={{
                  background: active ? W.ink : 'transparent',
                  border: active ? 'none' : `0.5px solid ${W.line}`,
                  color: active ? W.bg : W.ink2,
                  fontFamily: FONT_UI, fontSize: 12.5, fontWeight: 500,
                  padding: '7px 12px', borderRadius: 999, cursor: 'pointer',
                  whiteSpace: 'nowrap', display: 'flex', alignItems: 'center', gap: 6,
                }}>
                  {label}
                  <span style={{
                    fontSize: 10.5, color: active ? 'rgba(245,239,226,0.55)' : W.muted, fontWeight: 600,
                  }}>{n}</span>
                </button>
              );
            })}
          </div>

          {/* Vendor cards */}
          <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
            {filtered.length === 0 ? (
              <Card style={{ padding: 20, textAlign: 'center' }}>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontStyle: 'italic', fontSize: 14, color: W.muted,
                }}>No vendors match this filter.</div>
              </Card>
            ) : filtered.map((v) => (
              <VendorCard key={v.id} v={v} onClick={() => setEditing(v)}/>
            ))}
          </div>

          {/* Add vendor */}
          <div style={{ padding: '20px 16px 4px' }}>
            <button onClick={() => setEditing('new')} style={{
              width: '100%', padding: '14px 0',
              background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
              cursor: 'pointer',
              fontFamily: FONT_UI, fontSize: 14, fontWeight: 500,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            }}>
              <Icon name="plus" size={15} color={W.bg} strokeWidth={1.8}/>
              Add vendor
            </button>
          </div>
        </>
      )}

      {editing && (
        <FormSheet
          title={editing === 'new' ? 'Add a vendor' : 'Edit vendor'}
          eyebrow={editing === 'new' ? 'New entry' : 'Edit'}
          fields={vendorFields()}
          initial={editing === 'new' ? {} : editing}
          submitLabel={editing === 'new' ? 'Add' : 'Save'}
          onClose={() => setEditing(null)}
          onSubmit={submitVendor}
          onDelete={editing !== 'new' ? deleteCurrent : null}
        />
      )}
    </div>
  );
}

function EmptyVendors({ onAdd }) {
  return (
    <div style={{
      padding: '60px 28px 80px',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      textAlign: 'center',
    }}>
      <div style={{
        width: 64, height: 64, borderRadius: 999,
        background: W.cardSoft, border: `0.5px solid ${W.line}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 22,
      }}>
        <Icon name="flag" size={26} color={W.clay} strokeWidth={1.4}/>
      </div>
      <div style={{
        fontFamily: FONT_DISPLAY, fontSize: 28, fontWeight: 500,
        color: W.ink, letterSpacing: -0.3, lineHeight: 1.1,
      }}>Your vendor team,<br/>
        <span style={{ fontStyle: 'italic' }}>still to be chosen.</span>
      </div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13.5, color: W.muted,
        marginTop: 14, lineHeight: 1.55, maxWidth: 280,
      }}>
        Add each vendor as you book them — venue, florist, caterer, photographer.
        Payments and milestones track automatically.
      </div>
      <button onClick={onAdd} style={{
        marginTop: 28, padding: '14px 22px',
        background: W.ink, color: W.bg, border: 'none', borderRadius: 999,
        cursor: 'pointer',
        fontFamily: FONT_UI, fontSize: 14, fontWeight: 500,
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <Icon name="plus" size={15} color={W.bg} strokeWidth={1.8}/>
        Add your first vendor
      </button>
    </div>
  );
}

function VStat({ n, label, color }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
        <div style={{ width: 6, height: 6, borderRadius: 999, background: color }}/>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10, fontWeight: 600,
          letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase',
        }}>{label}</div>
      </div>
      <div style={{
        fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink, letterSpacing: -0.3, lineHeight: 1,
      }}>{n}</div>
    </div>
  );
}

function VendorCard({ v, onClick }) {
  const status = {
    paid:        { tone: 'sage',    label: 'Paid in full' },
    due:         { tone: 'amber',   label: 'Payment due'  },
    booked:      { tone: 'clay',    label: 'Booked'       },
    partial:     { tone: 'clay',    label: 'In progress'  },
    researching: { tone: 'neutral', label: 'Researching'  },
  }[v.status] || { tone: 'neutral', label: v.status || '—' };
  const pct = v.total ? v.paid / v.total : 0;
  const init = (v.name || '?').split(' ').slice(0, 2).map(s => s[0] || '').join('').toUpperCase() || '?';
  return (
    <Card onClick={onClick} style={{ padding: 14, cursor: onClick ? 'pointer' : 'default' }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{
          width: 40, height: 40, borderRadius: 12,
          background: '#fbf6ea', border: `0.5px solid ${W.lineSoft}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <div style={{
            fontFamily: FONT_DISPLAY, fontSize: 14, color: W.clayDeep, letterSpacing: -0.2,
          }}>{init}</div>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
            letterSpacing: 1.2, color: W.muted, textTransform: 'uppercase',
          }}>{v.role || 'Vendor'}</div>
          <div style={{
            fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500, color: W.ink,
            marginTop: 2, lineHeight: 1.2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{v.name || <span style={{ color: W.muted, fontStyle: 'italic' }}>(unnamed)</span>}</div>
        </div>
        <Pill tone={status.tone} style={{ padding: '3px 8px', fontSize: 9.5 }}>{status.label}</Pill>
      </div>

      {v.total > 0 && (
        <div style={{ marginTop: 12 }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginBottom: 6,
          }}>
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 16, color: W.ink, letterSpacing: -0.2,
            }}>
              {fmt$(v.paid)}
              <span style={{ color: W.muted, fontFamily: FONT_UI, fontSize: 12, marginLeft: 6 }}>
                of {fmt$(v.total)}
              </span>
            </div>
            <div style={{ fontFamily: FONT_UI, fontSize: 11.5, color: W.muted }}>
              {Math.round(pct * 100)}%
            </div>
          </div>
          <Bar value={Math.min(pct, 1)} color={v.status === 'due' ? W.amber : W.clay} height={3}/>
        </div>
      )}

      {v.next && (
        <div style={{
          marginTop: 12, paddingTop: 12, borderTop: `0.5px solid ${W.lineSoft}`,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <Icon name="calendar" size={13} color={W.muted} strokeWidth={1.4}/>
          <div style={{ fontFamily: FONT_UI, fontSize: 12.5, color: W.ink2, flex: 1 }}>
            {v.next}
          </div>
          <Icon name="chevron" size={12} color={W.faint}/>
        </div>
      )}
    </Card>
  );
}

Object.assign(window, { VendorsScreen });
