// Agent entry screen + confirmation screen.
// No global mock data — all state comes via props.

function AgentEntry({ me, today, streak, onSubmit, onOpenHistory, onLogout }) {
  const kpis = KPI_DEFS;
  const [values, setValues] = React.useState(() => zeroValues());
  const [note, setNote] = React.useState('');
  const [noteOpen, setNoteOpen] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const anyValue = Object.values(values).some(v => v > 0);
  const ink = REM.obsidian;
  const muted = REM.inkSubtle;
  const hair = 'rgba(26,26,26,.12)';

  const dateStr = fmtDate(today);
  const dow = fmtDayOfWeek(today);

  const submit = async () => {
    if (submitting || !anyValue) return;
    setSubmitting(true);
    try {
      await onSubmit(values, note);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%' }}>
      <PhoneChrome
        dark={false}
        left={<Press onClick={onOpenHistory} style={{ padding: 6 }}>
          <div style={{
            width: 34, height: 34, borderRadius: 999, background: 'rgba(26,26,26,.06)',
            display:'grid', placeItems:'center', fontFamily: REM.fontSub,
            fontSize: 11, fontWeight: 700, letterSpacing: '.1em', color: ink,
          }}>{me.initials}</div>
        </Press>}
        right={<Press onClick={onLogout} haptic={false} style={{ padding: 6 }}>
          <Eyebrow color={muted} size={9}>Sign out</Eyebrow>
        </Press>}
      />
      <div style={{ padding: '20px 20px 4px' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 10 }}>
          <Eyebrow color={muted}>{dow} · {dateStr}</Eyebrow>
          <Eyebrow color={muted}>Day {streak + 1}</Eyebrow>
        </div>
        <div style={{
          fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 40, lineHeight: 1.0,
          letterSpacing: '-0.025em', color: ink,
        }}>Today,<br/><span style={{ color: REM.deepTeal, fontStyle:'italic', fontWeight: 400 }}>kept.</span></div>
        <div style={{ marginTop: 12, color: muted, fontFamily: REM.fontBody, fontSize: 13, lineHeight: 1.5 }}>
          Seven numbers. One tap each. Submitted at day's end.
        </div>
      </div>

      <div style={{ flex: 1, overflow:'auto', marginTop: 16 }}>
        <div style={{ borderTop: `1px solid ${hair}` }}>
          {kpis.map(k => (
            <StepperRow
              key={k.id} label={k.label} value={values[k.id]} dark={false} size="md"
              onChange={v => setValues(s => ({ ...s, [k.id]: v }))}
            />
          ))}
        </div>

        <div style={{ padding: '18px 20px 0' }}>
          {!noteOpen ? (
            <Press onClick={() => setNoteOpen(true)} style={{ display:'flex', gap: 8, alignItems:'center' }}>
              <span style={{ fontFamily: REM.fontDisplay, fontSize: 18, color: muted, lineHeight: 1 }}>+</span>
              <Eyebrow color={muted}>Add note (optional)</Eyebrow>
            </Press>
          ) : (
            <textarea
              value={note} onChange={e => setNote(e.target.value)} autoFocus rows={2}
              placeholder="A line about the day…"
              style={{
                width:'100%', border:'none', outline:'none', resize:'none',
                borderBottom:`1px solid ${hair}`, background:'transparent',
                fontFamily: REM.fontBody, fontSize: 14, color: ink, padding: '8px 0',
              }}
            />
          )}
        </div>

        <div style={{ height: 24 }}/>
      </div>

      <PrimaryBar
        label={submitting ? 'Submitting…' : 'Submit today'}
        onClick={submit}
        dark={false}
        disabled={!anyValue || submitting}
        note={anyValue ? null : 'Enter at least one number to submit'}
      />
    </div>
  );
}

function AgentConfirmation({ me, submitted, wtdAfter, streakAfter, today, onDone }) {
  const kpis = KPI_DEFS;
  const ink = REM.obsidian;
  const muted = REM.inkSubtle;
  const hair = 'rgba(26,26,26,.12)';

  const [reveal, setReveal] = React.useState(false);
  React.useEffect(() => { const t = setTimeout(() => setReveal(true), 120); return () => clearTimeout(t); }, []);

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%', background: REM.linen }}>
      <PhoneChrome dark={false} />

      <div style={{ flex:1, overflow:'auto', padding:'8px 20px 20px' }}>
        <div style={{ padding:'24px 0 16px', borderBottom:`1px solid ${hair}` }}>
          <Eyebrow color={muted}>Logged · {fmtDate(today)}</Eyebrow>
          <div style={{
            marginTop: 14,
            fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 56, lineHeight: .98,
            letterSpacing: '-0.03em', color: ink,
          }}>Kept.</div>
          <div style={{ marginTop: 12, color: muted, fontFamily: REM.fontBody, fontSize: 14, lineHeight: 1.5, maxWidth: 280 }}>
            What you did today is on the record. A week builds from here.
          </div>
        </div>

        <div style={{ padding: '18px 0 8px' }}>
          <Eyebrow color={muted}>Today's entries</Eyebrow>
        </div>
        <div style={{ borderTop: `1px solid ${hair}` }}>
          {kpis.map(k => (
            <div key={k.id} style={{
              display:'flex', justifyContent:'space-between', alignItems:'baseline',
              padding: '12px 0', borderBottom: `1px solid ${hair}`,
            }}>
              <div style={{ fontFamily: REM.fontBody, fontSize: 14, color: ink }}>{k.label}</div>
              <div style={{
                fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 22, letterSpacing: '-0.02em',
                color: ink, fontVariantNumeric:'tabular-nums',
              }}>{submitted[k.id] || 0}</div>
            </div>
          ))}
        </div>

        <div style={{ padding: '22px 0 10px' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
            <Eyebrow color={muted}>Week-to-date vs target</Eyebrow>
            <Eyebrow color={muted}>Mon–Fri</Eyebrow>
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap: 16 }}>
          {kpis.map((k, i) => {
            const have = wtdAfter[k.id] || 0;
            const target = me.targets[k.id] || 0;
            const pct = target > 0 ? Math.round((have / target) * 100) : 0;
            return (
              <div key={k.id}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom: 8 }}>
                  <div style={{ fontFamily: REM.fontBody, fontSize: 14, color: ink }}>{k.label}</div>
                  <div style={{ fontFamily: REM.fontBody, fontSize: 13, color: muted, fontVariantNumeric:'tabular-nums' }}>
                    {have} <span style={{ opacity:.5 }}>/ {target}</span>
                  </div>
                </div>
                <div style={{ width: reveal ? '100%' : '0%', transition: 'width 500ms ease', transitionDelay: `${i*60}ms` }}>
                  <ProgressBar pct={pct} dark={false} accent={REM.obsidian}/>
                </div>
              </div>
            );
          })}
        </div>

        <div style={{
          marginTop: 28, padding: '22px 20px',
          background: '#fff', border: `1px solid ${hair}`,
        }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
            <Eyebrow color={REM.deepTeal}>Streak</Eyebrow>
            <Eyebrow color={muted}>{fmtDate(today)}</Eyebrow>
          </div>
          <div style={{
            marginTop: 14, display:'flex', alignItems:'baseline', gap: 12,
            fontFamily: REM.fontDisplay, fontWeight: 500, fontSize: 64, lineHeight: 1,
            letterSpacing: '-0.03em', color: ink,
          }}>
            {streakAfter}<span style={{ fontFamily: REM.fontBody, fontSize: 14, color: muted, fontWeight: 400, letterSpacing: 0 }}>days in a row</span>
          </div>
          <div style={{ marginTop: 16, display:'flex', gap: 5 }}>
            {Array.from({length: 14}).map((_, i) => {
              const on = i < Math.min(14, streakAfter);
              return <div key={i} style={{ flex:1, height: 4, background: on ? REM.obsidian : 'rgba(26,26,26,.12)' }}/>;
            })}
          </div>
          <div style={{ marginTop: 14, color: muted, fontFamily: REM.fontBody, fontSize: 12.5, lineHeight: 1.5 }}>
            Weekends do not break the streak.
          </div>
        </div>
      </div>

      <PrimaryBar label="Done" onClick={onDone} dark={false}/>
    </div>
  );
}

Object.assign(window, { AgentEntry, AgentConfirmation });
