// Savings goals + Insights + Categories pages.

const PageSavings = () => {
  const { state, addGoal, updateGoal, deleteGoal, loadDemo } = useAppState();
  const [showAdd, setShowAdd] = React.useState(false);

  return (
    <div>
      <div className="topbar">
        <div>
          <h1 className="page-title">Savings <span className="serif">goals</span></h1>
          <div className="page-sub">{state.goals.length} goals tracked</div>
        </div>
        <div className="row" style={{gap:8}}>
          {state.goals.length === 0 && state.transactions.length === 0 && (
            <button className="btn" onClick={loadDemo}><IPlay size={13}/> Load demo</button>
          )}
          <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> New goal</button>
        </div>
      </div>

      {state.goals.length === 0 ? (
        <div className="empty">
          <div className="empty-icon"><ITarget size={22}/></div>
          <h3 className="serif" style={{fontSize:22}}>No goals yet</h3>
          <p>Set targets like an emergency fund, a December holiday, or a deposit. We'll help you get there.</p>
          <button className="btn btn-primary" onClick={() => setShowAdd(true)}><IPlus size={14}/> Add a goal</button>
        </div>
      ) : (
        <div className="grid stagger" style={{gridTemplateColumns:'repeat(2, 1fr)', gap:18}}>
          {state.goals.map(g => {
            const pct = g.target ? Math.min(1, g.saved / g.target) : 0;
            const remaining = Math.max(0, g.target - g.saved);
            const member = state.members.find(m => m.id === g.memberId);
            return (
              <div key={g.id} className="card card-pad-lg hov">
                <div className="row-between" style={{marginBottom:14}}>
                  <div>
                    <div style={{fontSize:11, color:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:500}}>Goal</div>
                    <div className="serif" style={{fontSize:24, marginTop:2, letterSpacing:'-0.01em'}}>{g.name}</div>
                  </div>
                  <button className="btn btn-ghost btn-sm" onClick={() => deleteGoal(g.id)}><ITrash size={13}/></button>
                </div>

                {/* Big radial */}
                <div style={{position:'relative', display:'flex', justifyContent:'center', marginBottom:18}}>
                  <RadialProgress pct={pct} size={140}/>
                </div>

                <div className="row-between" style={{marginBottom:10}}>
                  <div>
                    <div style={{fontSize:11, color:'var(--ink-3)'}}>Saved</div>
                    <div className="mono" style={{fontWeight:500, fontSize:15}}>{fmtZAR(g.saved, {cents:false})}</div>
                  </div>
                  <div style={{textAlign:'right'}}>
                    <div style={{fontSize:11, color:'var(--ink-3)'}}>Target</div>
                    <div className="mono" style={{fontWeight:500, fontSize:15}}>{fmtZAR(g.target, {cents:false})}</div>
                  </div>
                </div>

                <div style={{padding:'10px 12px', background:'var(--surface-2)', borderRadius:10, fontSize:12, color:'var(--ink-2)', marginTop:6}}>
                  <span style={{color:'var(--ink-3)'}}>Still need</span> <span className="mono" style={{fontWeight:500, color:'var(--ink)'}}>{fmtZAR(remaining, {cents:false})}</span>
                  {state.mode === 'household' && member && <span style={{marginLeft:8, color:'var(--ink-3)'}}>· {member.name}</span>}
                </div>

                <div className="row" style={{gap:8, marginTop:14}}>
                  <button className="btn btn-sm" style={{flex:1, justifyContent:'center'}} onClick={() => {
                    const v = prompt('Add to this goal (R):', '500');
                    const n = parseFloat(v);
                    if (n > 0) updateGoal(g.id, { saved: Math.min(g.target, g.saved + n) });
                  }}><IPlus size={12}/> Contribute</button>
                  <button className="btn btn-sm" style={{flex:1, justifyContent:'center'}} onClick={() => {
                    const v = prompt('Withdraw (R):', '100');
                    const n = parseFloat(v);
                    if (n > 0) updateGoal(g.id, { saved: Math.max(0, g.saved - n) });
                  }}><IMinus size={12}/> Withdraw</button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {showAdd && (
        <AddGoalModal onClose={() => setShowAdd(false)} onAdd={g => { addGoal(g); setShowAdd(false); }}/>
      )}
    </div>
  );
};

const RadialProgress = ({ pct, size = 120 }) => {
  const r = size / 2 - 8;
  const C = 2 * Math.PI * r;
  const [drawn, setDrawn] = React.useState(0);
  React.useEffect(() => {
    const t = setTimeout(() => setDrawn(pct), 60);
    return () => clearTimeout(t);
  }, [pct]);
  const animatedPct = useCountUp(pct * 100);
  return (
    <div style={{position:'relative', width:size, height:size}}>
      <svg width={size} height={size} style={{transform:'rotate(-90deg)'}}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--line-2)" strokeWidth="8"/>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--mint-deep)" strokeWidth="8"
          strokeLinecap="round"
          strokeDasharray={C}
          strokeDashoffset={C - C * drawn}
          style={{transition:'stroke-dashoffset 1.2s cubic-bezier(0.2,0.8,0.2,1)'}}
        />
      </svg>
      <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column'}}>
        <div className="serif" style={{fontSize:30, lineHeight:1, fontVariantNumeric:'tabular-nums'}}>{animatedPct.toFixed(0)}%</div>
        <div style={{fontSize:10, color:'var(--ink-3)', marginTop:2, textTransform:'uppercase', letterSpacing:'0.06em'}}>complete</div>
      </div>
    </div>
  );
};

const AddGoalModal = ({ onClose, onAdd }) => {
  const { state } = useAppState();
  const [name, setName] = React.useState('');
  const [target, setTarget] = React.useState('');
  const [saved, setSaved] = React.useState('0');
  const [memberId, setMemberId] = React.useState(state.members[0]?.id);

  const submit = (e) => {
    e.preventDefault();
    onAdd({
      name: name.trim() || 'New goal',
      target: parseFloat(target) || 0,
      saved: parseFloat(saved) || 0,
      memberId,
    });
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="row-between" style={{marginBottom:18}}>
          <div className="serif" style={{fontSize:24}}>New goal</div>
          <button className="btn btn-ghost btn-sm" onClick={onClose}><IClose size={16}/></button>
        </div>
        <form onSubmit={submit} className="grid" style={{gap:14}}>
          <div className="field">
            <label className="label">What are you saving for?</label>
            <input className="input" value={name} onChange={e => setName(e.target.value)} placeholder="e.g. Emergency fund" autoFocus required/>
          </div>
          <div className="grid" style={{gridTemplateColumns:'1fr 1fr', gap:12}}>
            <div className="field">
              <label className="label">Target (R)</label>
              <input className="input" type="number" value={target} onChange={e => setTarget(e.target.value)} required/>
            </div>
            <div className="field">
              <label className="label">Already saved</label>
              <input className="input" type="number" value={saved} onChange={e => setSaved(e.target.value)}/>
            </div>
          </div>
          {state.mode === 'household' && (
            <div className="field">
              <label className="label">Whose goal</label>
              <div className="row" style={{gap:8, flexWrap:'wrap'}}>
                {state.members.map(m => (
                  <button type="button" key={m.id} className="member-chip" style={{
                    cursor:'pointer',
                    borderColor: memberId === m.id ? 'var(--ink)' : 'var(--line)',
                  }} onClick={() => setMemberId(m.id)}>
                    <span className="avatar" style={{background: m.color}}>{m.initials}</span>
                    {m.name}
                  </button>
                ))}
              </div>
            </div>
          )}
          <div className="row" style={{gap:8, marginTop:6}}>
            <button type="button" className="btn" style={{flex:1, justifyContent:'center'}} onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" style={{flex:1, justifyContent:'center'}}>Create goal</button>
          </div>
        </form>
      </div>
    </div>
  );
};

Object.assign(window, { PageSavings, RadialProgress, AddGoalModal });
