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

const BUDGET_ICONS = [
  { value: 'home',    label: 'Venue'    },
  { value: 'cake',    label: 'Catering' },
  { value: 'camera',  label: 'Photo'    },
  { value: 'leaf',    label: 'Florals'  },
  { value: 'music',   label: 'Music'    },
  { value: 'sparkle', label: 'Beauty'   },
  { value: 'flag',    label: 'Paper'    },
  { value: 'rings',   label: 'Rings'    },
  { value: 'arrow',   label: 'Transport'},
  { value: 'heart',   label: 'Travel'   },
  { value: 'wallet',  label: 'Other'    },
];

function categoryFields() {
  return [
    { name: 'name',    label: 'Category name', type: 'text',
      placeholder: 'e.g. Venue, Florals, Photography' },
    { name: 'planned', label: 'Planned amount', type: 'number',
      min: 0, max: 200000, step: 100, default: 0, unit: '$' },
    { name: 'spent',   label: 'Spent so far',   type: 'number',
      min: 0, max: 200000, step: 100, default: 0, unit: '$' },
    { name: 'icon',    label: 'Icon',           type: 'choice',
      options: BUDGET_ICONS },
    { name: 'note',    label: 'Note',           type: 'text',
      placeholder: 'Optional — e.g. "Includes day-of staff"' },
  ];
}

function BudgetScreen() {
  const budget = useBudget();
  const [filter, setFilter] = React.useState('all');
  const [editing, setEditing] = React.useState(null);

  const totalPct = budget.total ? budget.spent / budget.total : 0;
  const filtered = budget.categories.filter(c => {
    if (filter === 'all') return true;
    if (filter === 'attention') return c.status === 'over';
    return c.status === filter;
  });

  const isEmpty = budget.categories.length === 0;

  const submitCategory = (values) => {
    const norm = {
      ...values,
      planned: Number(values.planned) || 0,
      spent:   Number(values.spent)   || 0,
    };
    if (editing === 'new') budget.addCategory(norm);
    else budget.updateCategory(editing.id, norm);
    setEditing(null);
  };

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

  return (
    <div style={{ background: W.bg, paddingBottom: 28, position: 'relative' }}>
      <div style={{ paddingTop: 56 }}/>
      <ScreenHeader eyebrow="Budget" title={fmt$(budget.total) + ' plan'}/>

      {isEmpty ? (
        <EmptyBudget onAdd={() => setEditing('new')}/>
      ) : (
        <>
          {/* Hero */}
          <div style={{ padding: '8px 16px 16px' }}>
            <Card style={{ padding: 22 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                <div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
                    letterSpacing: 1.4, textTransform: 'uppercase', color: W.muted,
                  }}>{budget.remaining >= 0 ? 'Remaining' : 'Over plan'}</div>
                  <div style={{
                    fontFamily: FONT_DISPLAY, fontSize: 52, fontWeight: 500,
                    color: budget.remaining >= 0 ? W.ink : W.red,
                    letterSpacing: -1.6, lineHeight: 0.95, marginTop: 6,
                  }}>{fmt$(Math.abs(budget.remaining))}</div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 13, color: W.ink2, marginTop: 10,
                  }}>
                    of {fmt$(budget.total)} planned
                  </div>
                </div>
                <ProgressRing value={totalPct} size={78} stroke={6}
                  color={totalPct > 1 ? W.red : W.clay}>
                  <div style={{
                    fontFamily: FONT_DISPLAY, fontSize: 22, color: W.ink,
                    letterSpacing: -0.4, lineHeight: 1,
                  }}>{Math.round(totalPct * 100)}%</div>
                </ProgressRing>
              </div>

              {/* Stacked contributor bar — still from globals; contributors come in a follow-up slice */}
              <div style={{ marginTop: 22 }}>
                <div style={{
                  fontFamily: FONT_UI, fontSize: 11, fontWeight: 600,
                  letterSpacing: 0.8, textTransform: 'uppercase', color: W.muted,
                  marginBottom: 10,
                }}>Contributors</div>
                <div style={{
                  display: 'flex', width: '100%', height: 10, borderRadius: 999,
                  overflow: 'hidden', background: '#ece2cd',
                }}>
                  {BUDGET.contributors.map((c, i) => (
                    <div key={i} style={{
                      width: `${(c.amount / budget.total) * 100}%`,
                      background: c.color,
                      borderRight: i < BUDGET.contributors.length - 1 ? '1.5px solid #fff' : 'none',
                    }}/>
                  ))}
                </div>
                <div style={{
                  display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12,
                }}>
                  {BUDGET.contributors.map((c, i) => (
                    <div key={i} style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                    }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                        <div style={{
                          width: 9, height: 9, borderRadius: 3, background: c.color,
                        }}/>
                        <div style={{
                          fontFamily: FONT_UI, fontSize: 13, color: W.ink2,
                        }}>{c.name}</div>
                      </div>
                      <div style={{
                        fontFamily: FONT_DISPLAY, fontSize: 15, color: W.ink, letterSpacing: -0.1,
                      }}>{fmt$(c.amount)}</div>
                    </div>
                  ))}
                </div>
              </div>
            </Card>
          </div>

          {/* Overspend alert — only if any */}
          {budget.overspend > 0 && (
            <div style={{ padding: '0 16px 18px' }}>
              <div style={{
                background: '#f6e6c8', borderRadius: 16,
                padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 12,
                border: `0.5px solid #ecd6a6`,
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: 999, background: '#e9c97a',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: '#5a3e0a', fontFamily: FONT_DISPLAY, fontWeight: 600, fontSize: 17,
                  flexShrink: 0,
                }}>!</div>
                <div style={{ flex: 1 }}>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 13.5, fontWeight: 500, color: '#5a3e0a',
                  }}>
                    {budget.statusCounts.over === 1
                      ? `1 category is over plan`
                      : `${budget.statusCounts.over} categories are over plan`}
                  </div>
                  <div style={{
                    fontFamily: FONT_UI, fontSize: 12, color: '#7a5320', marginTop: 1,
                  }}>{fmt$(budget.overspend)} over — adjust allocation or trim</div>
                </div>
                <Icon name="chevron" size={14} color="#7a5320"/>
              </div>
            </div>
          )}

          {/* Filter chips */}
          <div style={{
            display: 'flex', gap: 8, padding: '0 22px 14px',
            overflowX: 'auto',
          }}>
            {[
              ['all',       'All',             budget.categories.length],
              ['attention', 'Needs attention', budget.statusCounts.over],
              ['paid',      'Paid',            budget.statusCounts.paid],
              ['partial',   'In progress',     budget.statusCounts.partial],
              ['open',      'Open',            budget.statusCounts.open],
            ].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>

          <SectionTitle eyebrow="Categories" title="Where it goes"/>
          <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 categories match this filter.</div>
              </Card>
            ) : filtered.map(c => (
              <CategoryRow key={c.id} c={c} onClick={() => setEditing(c)}/>
            ))}
          </div>

          {/* Add category */}
          <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 category
            </button>
          </div>

          {/* Paid to date */}
          <div style={{ padding: '20px 16px 16px' }}>
            <Card style={{ padding: 18, background: W.cardSoft }}>
              <div style={{
                fontFamily: FONT_UI, fontSize: 11, fontWeight: 600,
                letterSpacing: 1.2, textTransform: 'uppercase', color: W.muted,
              }}>Paid to date</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginTop: 6 }}>
                <div style={{
                  fontFamily: FONT_DISPLAY, fontSize: 30, color: W.ink, letterSpacing: -0.6,
                }}>{fmt$(budget.paidToDate)}</div>
                <div style={{ fontFamily: FONT_UI, fontSize: 12.5, color: W.muted }}>
                  · {fmt$(Math.max(0, budget.spent - budget.paidToDate))} committed
                </div>
              </div>
              <Bar value={budget.total ? budget.paidToDate / budget.total : 0} color={W.sage} height={6}/>
            </Card>
          </div>
        </>
      )}

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

function EmptyBudget({ 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="wallet" 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 budget,<br/>
        <span style={{ fontStyle: 'italic' }}>a clean slate.</span>
      </div>
      <div style={{
        fontFamily: FONT_UI, fontSize: 13.5, color: W.muted,
        marginTop: 14, lineHeight: 1.55, maxWidth: 280,
      }}>
        Add categories one by one — Venue, Catering, Florals, Music… The totals
        and alerts add up automatically as you spend.
      </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 category
      </button>
    </div>
  );
}

function CategoryRow({ c, onClick }) {
  const pct = c.planned ? c.spent / c.planned : 0;
  const statusMeta = {
    paid:    { tone: 'sage',    label: 'Paid' },
    partial: { tone: 'clay',    label: 'In progress' },
    over:    { tone: 'amber',   label: 'Over plan' },
    open:    { tone: 'neutral', label: 'Open' },
  }[c.status] || { tone: 'neutral', label: c.status };
  const barColor = c.status === 'over' ? W.amber : (c.status === 'paid' ? W.sage : W.clay);

  return (
    <Card onClick={onClick} style={{ padding: 14, cursor: onClick ? 'pointer' : 'default' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: '#fbf6ea', border: `0.5px solid ${W.lineSoft}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          flexShrink: 0,
        }}>
          <Icon name={c.icon || 'sparkle'} size={16} color={W.clayDeep} strokeWidth={1.4}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
          }}>
            <div style={{
              fontFamily: FONT_UI, fontSize: 14.5, fontWeight: 500, color: W.ink,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              maxWidth: 200,
            }}>{c.name}</div>
            <div style={{
              fontFamily: FONT_DISPLAY, fontSize: 16, color: W.ink, letterSpacing: -0.2,
            }}>{fmt$(c.spent)}</div>
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 3,
          }}>
            <Pill tone={statusMeta.tone} style={{ padding: '2px 7px', fontSize: 9.5 }}>{statusMeta.label}</Pill>
            <div style={{ fontFamily: FONT_UI, fontSize: 11, color: W.muted }}>
              of {fmt$(c.planned)}
            </div>
          </div>
        </div>
      </div>
      <div style={{ marginTop: 11 }}>
        <Bar value={Math.min(pct, 1)} color={barColor} height={3}/>
      </div>
      {c.note && (
        <div style={{
          fontFamily: FONT_UI, fontSize: 11.5, color: c.status === 'over' ? W.amber : W.muted,
          marginTop: 8, fontStyle: 'italic',
        }}>{c.note}</div>
      )}
    </Card>
  );
}

function ScreenHeader({ eyebrow, title, right }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
      padding: '8px 22px 18px',
    }}>
      <div>
        <div style={{
          fontFamily: FONT_UI, fontSize: 10.5, fontWeight: 600,
          letterSpacing: 1.8, textTransform: 'uppercase', color: W.muted,
        }}>{eyebrow}</div>
        <div style={{
          fontFamily: FONT_DISPLAY, fontSize: 34, fontWeight: 500,
          color: W.ink, letterSpacing: -0.6, lineHeight: 1, marginTop: 4,
        }}>{title}</div>
      </div>
      {right || null}
    </div>
  );
}

Object.assign(window, { BudgetScreen, ScreenHeader });
