// Komonichi — Objectives page. Add only, no edit.
const { useKomonichi, actions, sel } = window.KomonichiState;

const SCALES = [
  { key: 'yearly',    label: 'year',    eyebrow: 'the long horizon',  tone: 'warm',   parentKey: null },
  { key: 'quarterly', label: 'quarter', eyebrow: 'a season',           tone: 'indigo', parentKey: 'yearly' },
  { key: 'monthly',   label: 'month',   eyebrow: 'a moon',             tone: 'moss',   parentKey: 'quarterly' },
  { key: 'weekly',    label: 'week',    eyebrow: 'seven mornings',     tone: 'gold',   parentKey: 'monthly' },
];

function ObjectivesPage() {
  const [state] = useKomonichi();

  return (
    <div className="fade-in">
      <div style={{ marginBottom: 22 }}>
        <div className="label">written in ink, not pencil</div>
        <h2 className="display" style={{ fontSize: 48, lineHeight: 1, margin: '8px 0 0' }}>
          objectives, <span style={{ color: 'var(--persimmon)' }}>once set</span>
        </h2>
        <div className="haiku" style={{ marginTop: 14, maxWidth: 620 }}>
          An objective, once written, cannot be unwritten — only completed, or quietly outgrown. The tasks change daily. The direction does not.
        </div>
      </div>

      <div className="brush" style={{ marginBottom: 22 }}></div>

      <div className="grid g-12">
        {SCALES.map(s => (
          <div key={s.key} className="c-6">
            <ObjectiveColumn scale={s} state={state} />
          </div>
        ))}
      </div>
    </div>
  );
}

function ObjectiveColumn({ scale, state }) {
  const [adding, setAdding] = React.useState(false);
  const [text, setText] = React.useState('');
  const [parent, setParent] = React.useState('');
  const items = state.objectives[scale.key];

  const parents = scale.parentKey ? state.objectives[scale.parentKey] : [];

  const submit = (e) => {
    e.preventDefault();
    if (!text.trim()) return;
    actions.addObjective(text, scale.key, parent || null);
    setText(''); setParent(''); setAdding(false);
  };

  return (
    <div className="card" style={{ height: '100%' }}>
      <div className="cap">
        <div>
          <div className="label">{scale.eyebrow}</div>
          <h3 className="title"><span className="em">{scale.label}</span></h3>
        </div>
        <button className="btn ghost tiny" onClick={() => setAdding(a => !a)}>+ add</button>
      </div>

      {adding && (
        <form onSubmit={submit} className="fade-in" style={{ padding: '12px 0 18px', borderBottom: '1px dashed var(--paper-line)', marginBottom: 12 }}>
          <input className="f" autoFocus placeholder={`a ${scale.label}'s direction…`} value={text} onChange={e => setText(e.target.value)} style={{ marginBottom: 10 }} />
          {scale.parentKey && parents.length > 0 && (
            <div style={{ marginBottom: 10 }}>
              <div className="label" style={{ marginBottom: 4 }}>drawn from the {scale.parentKey.replace('ly','')}</div>
              {React.createElement(window.ThemedSelect, {
                value: parent,
                onChange: setParent,
                placeholder: '— stand alone —',
                options: [
                  { value: '', label: '— stand alone —' },
                  ...parents.map(p => ({ value: p.id, label: p.text })),
                ],
              })}
            </div>
          )}
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button type="button" className="btn ghost tiny" onClick={() => setAdding(false)}>cancel</button>
            <button type="submit" className="btn warm tiny">commit</button>
          </div>
          <div className="label" style={{ marginTop: 10, fontSize: 9, color: 'var(--persimmon)', opacity: 0.8 }}>
            once committed, this text cannot be changed.
          </div>
        </form>
      )}

      {items.length === 0 && !adding && (
        <div className="haiku" style={{ fontSize: 14, padding: '14px 0' }}>
          <span className="line">Nothing yet committed.</span>
          <span className="line">The page stays open, waiting</span>
          <span className="line">for the first brush stroke.</span>
        </div>
      )}

      <div>
        {items.filter(o => o.status !== 'archived').map((o, i, arr) => {
          const parentObj = o.parent_id ? sel.objectiveById(o.parent_id) : null;
          const linkedTasks = state.tasks.filter(t => t.objectiveId === o.id);
          const doneTasks = linkedTasks.filter(t => t.status === 'done').length;
          const pct = linkedTasks.length > 0 ? Math.round((doneTasks / linkedTasks.length) * 100) : 0;
          return (
            <div key={o.id} style={{ padding: '14px 0', borderBottom: i < arr.length - 1 ? '1px dashed var(--paper-line)' : 0, opacity: o.seeded ? 0.65 : 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
                <div className="display" style={{ fontSize: 18, color: 'var(--ink)', fontStyle: o.seeded ? 'italic' : 'normal' }}>
                  {o.text}
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  {o.seeded ? <span className="chip locked">example</span> : null}
                  <span className={`chip ${scale.tone}`}>{o.period}</span>
                </div>
              </div>
              {parentObj && (
                <div className="label" style={{ marginTop: 6, opacity: 0.75 }}>↑ {parentObj.text}</div>
              )}
              {linkedTasks.length > 0 && (
                <div style={{ marginTop: 10 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 5 }}>
                    <div className="label">progress · {doneTasks}/{linkedTasks.length} kept</div>
                    <div className="num" style={{ fontSize: 11, color: 'var(--ink-faint)' }}>{pct}%</div>
                  </div>
                  <div style={{ height: 2, background: 'var(--paper-line)' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: 'var(--persimmon)', transition: 'width 0.8s ease' }}></div>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.ObjectivesPage = ObjectivesPage;
