const QUICK_CHIPS = ['Слушалась', 'Помогла по дому', 'Споры с братом', 'Домашка', 'Истерика', 'Сама прибралась'];

const RatingComposer = ({ day, child }) => {
  const { saveRating } = useRatings();
  const initialRating = day && !day.isDefault ? day.rating : 0;
  const [rating, setRating] = React.useState(initialRating);
  const [comment, setComment] = React.useState(day?.comment || '');
  const [saved, setSaved] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [focused, setFocused] = React.useState(false);

  React.useEffect(() => {
    setRating(day && !day.isDefault ? day.rating : 0);
    setComment(day?.comment || '');
  }, [day?.date]);

  const save = async () => {
    if (saving) return;
    setSaving(true);
    try {
      await saveRating({ date: day.date, rating: rating || 5, comment });
      setSaved(true);
      setTimeout(() => setSaved(false), 2200);
    } catch (e) {
      alert('Не удалось сохранить: ' + (e.message || e.status));
    } finally {
      setSaving(false);
    }
  };

  const existing = day && !day.isDefault;
  const childName = child?.name || 'ребёнка';

  return (
    <Card style={{ padding: 24, background:'linear-gradient(180deg, var(--surface) 0%, #FAF7F2 100%)' }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom: 18, flexWrap:'wrap', gap: 12 }}>
        <div>
          <div className="mono" style={{ fontSize: 11, color:'var(--fg-subtle)', letterSpacing:'.08em', textTransform:'uppercase', marginBottom: 4 }}>
            {day?.date === todayISO() ? 'СЕГОДНЯ' : 'ДЕНЬ'} · {fmtDateFull(day.date).toUpperCase()}
          </div>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing:'-.01em' }}>
            {existing ? 'Обновить оценку' : `Как прошёл день у ${childName}?`}
          </h2>
        </div>
        {existing && <Pill tone="good"><IconCheck size={10} stroke={2.5}/> УЖЕ ОТМЕЧЕНО</Pill>}
        {day?.isDefault && <Pill tone="warn">ПО УМОЛЧАНИЮ · 5★</Pill>}
      </div>

      <div style={{ display:'flex', alignItems:'center', gap: 20, marginBottom: 18, flexWrap:'wrap' }}>
        <StarRating value={rating} onChange={setRating} size={32} showLabel/>
      </div>

      <div style={{ position:'relative', marginBottom: 12 }}>
        <textarea
          placeholder="Что запомнилось? Похвала или замечание — пара слов."
          value={comment}
          onChange={e=> setComment(e.target.value)}
          onFocus={()=> setFocused(true)}
          onBlur={()=> setFocused(false)}
          rows={3}
          maxLength={280}
          style={{
            width:'100%', padding: 14, resize:'vertical',
            background:'var(--surface)',
            border:`1px solid ${focused ? 'var(--fg)' : 'var(--border)'}`,
            borderRadius: 12, fontSize: 14, color:'var(--fg)', outline:'none',
            transition:'border-color .15s ease', fontFamily:'inherit', lineHeight: 1.5,
          }}
        />
        <div className="mono" style={{ position:'absolute', bottom: 10, right: 14, fontSize: 10, color:'var(--fg-subtle)' }}>
          {comment.length}/280
        </div>
      </div>

      <div style={{ display:'flex', gap: 6, marginBottom: 16, flexWrap:'wrap' }}>
        {QUICK_CHIPS.map(c => (
          <button key={c} type="button" onClick={()=> setComment(comment ? `${comment} #${c.toLowerCase()}` : `#${c.toLowerCase()}`)}
            style={{
              padding:'5px 10px', borderRadius: 999, border:'1px solid var(--border)',
              background:'var(--surface)', color:'var(--fg-muted)', fontSize: 12, cursor:'pointer',
              transition:'border-color .15s ease, color .15s ease'
            }}
            onMouseEnter={e=>{ e.currentTarget.style.borderColor='var(--fg)'; e.currentTarget.style.color='var(--fg)'; }}
            onMouseLeave={e=>{ e.currentTarget.style.borderColor='var(--border)'; e.currentTarget.style.color='var(--fg-muted)'; }}
          >
            + {c}
          </button>
        ))}
      </div>

      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap: 12, flexWrap:'wrap' }}>
        <div style={{ fontSize: 12, color:'var(--fg-subtle)', lineHeight: 1.5, maxWidth: 380 }}>
          {!rating && !comment && 'Если оставить пустым, день засчитается как 5★ по умолчанию.'}
          {rating > 0 && `Будет сохранено как ${rating}/5`}
        </div>
        <Button variant="accent" size="md" onClick={save} disabled={saving} leading={saved ? <IconCheck size={16}/> : null}>
          {saving ? 'Сохраняем…' : saved ? 'Сохранено' : existing ? 'Обновить' : 'Сохранить'}
        </Button>
      </div>
    </Card>
  );
};

Object.assign(window, { RatingComposer });
