// Forge modal — create a new mission

const DAYS = [
  { key: 'seg', label: 'Seg' },
  { key: 'ter', label: 'Ter' },
  { key: 'qua', label: 'Qua' },
  { key: 'qui', label: 'Qui' },
  { key: 'sex', label: 'Sex' },
  { key: 'sab', label: 'Sab' },
  { key: 'dom', label: 'Dom' },
];
const DAY_ORDER = DAYS.map((d) => d.key);

const recurrenceLabel = (rec) => {
  if (!rec) return null;
  if (rec === 'daily')    return 'Todo dia';
  if (rec === 'weekdays') return 'Seg – Sex';
  if (rec === 'weekend')  return 'Sab – Dom';
  const map = { seg:'Seg', ter:'Ter', qua:'Qua', qui:'Qui', sex:'Sex', sab:'Sab', dom:'Dom' };
  return rec.split(',').map((d) => map[d] || d).join(', ');
};

const computeRec = (days) => {
  const sorted = [...days].sort((a, b) => DAY_ORDER.indexOf(a) - DAY_ORDER.indexOf(b));
  if (sorted.length === 7) return 'daily';
  const wd = ['seg','ter','qua','qui','sex'];
  if (sorted.length === 5 && wd.every((d) => sorted.includes(d))) return 'weekdays';
  if (sorted.length === 2 && ['sab','dom'].every((d) => sorted.includes(d))) return 'weekend';
  return sorted.join(',');
};

window.recurrenceLabel = recurrenceLabel;

const Forge = ({ onClose, onCreate }) => {
  const [title,        setTitle]        = React.useState('');
  const [desc,         setDesc]         = React.useState('');
  const [rarity,       setRarity]       = React.useState('rare');
  const [category,     setCategory]     = React.useState('work');
  const [recurring,    setRecurring]    = React.useState(false);
  const [deadline,     setDeadline]     = React.useState('Hoje');
  const [selectedDays, setSelectedDays] = React.useState(['seg','ter','qua','qui','sex']);

  const xp = DIFFICULTIES.find((d) => d.id === rarity).xp;

  const toggleDay = (day) =>
    setSelectedDays((days) =>
      days.includes(day)
        ? days.length > 1 ? days.filter((d) => d !== day) : days
        : [...days, day]
    );

  const setPreset = (preset) => {
    if (preset === 'all')      setSelectedDays(['seg','ter','qua','qui','sex','sab','dom']);
    if (preset === 'weekdays') setSelectedDays(['seg','ter','qua','qui','sex']);
    if (preset === 'weekend')  setSelectedDays(['sab','dom']);
  };

  const submit = () => {
    if (!title.trim()) return;
    if (recurring && selectedDays.length === 0) return;
    const recurrence = recurring ? computeRec(selectedDays) : null;
    onCreate({ title: title.trim(), desc: desc.trim() || 'Sem descrição', rarity, category, deadline, recurrence });
    onClose();
  };

  const isAllDays      = selectedDays.length === 7;
  const isWeekdaysPre  = selectedDays.length === 5 && ['seg','ter','qua','qui','sex'].every((d) => selectedDays.includes(d));
  const isWeekendPre   = selectedDays.length === 2 && ['sab','dom'].every((d) => selectedDays.includes(d));

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-h">
          <div>
            <div className="eyebrow">Forja de missões</div>
            <h2>Forjar nova missão</h2>
            <p>Defina o objetivo, a categoria e como ela se repete.</p>
          </div>
          <button className="icon-btn" onClick={onClose}><I.x /></button>
        </div>

        <div className="modal-body">
          <div className="field">
            <label>Título da missão</label>
            <input className="input" placeholder="Ex.: Estudar inglês 1h" value={title} onChange={(e) => setTitle(e.target.value)} autoFocus />
          </div>

          <div className="field">
            <label>Critério de conclusão</label>
            <textarea className="textarea" placeholder="O que precisa estar feito para considerar a missão completa?" value={desc} onChange={(e) => setDesc(e.target.value)} />
          </div>

          <div className="field">
            <label>Categoria</label>
            <div className="cat-row">
              {CATEGORIES.map((c) => {
                const Ico = I[c.ico];
                return (
                  <button key={c.id} className={`cat-pill ${category === c.id ? 'on' : ''}`} onClick={() => setCategory(c.id)}>
                    <Ico /> {c.label}
                  </button>
                );
              })}
            </div>
          </div>

          <div className="field">
            <label>Dificuldade · define a recompensa</label>
            <div className="diff-row">
              {DIFFICULTIES.map((d) => (
                <button key={d.id} className={`diff-pill ${rarity === d.id ? 'on' : ''}`} data-r={d.rarity} onClick={() => setRarity(d.id)}>
                  <div className="lab">{d.label}</div>
                  <div className="xp">+{d.xp} XP</div>
                </button>
              ))}
            </div>
          </div>

          {/* ── Frequency ── */}
          <div className="field">
            <label>Frequência</label>
            <div className="diff-row" style={{ gridTemplateColumns: 'repeat(2,1fr)' }}>
              <button className={`diff-pill ${!recurring ? 'on' : ''}`} data-r="rare" onClick={() => setRecurring(false)}>
                <div className="lab">Uma vez</div>
                <div className="xp">prazo fixo</div>
              </button>
              <button className={`diff-pill ${recurring ? 'on' : ''}`} data-r="epic" onClick={() => setRecurring(true)}>
                <div className="lab">↻ Recorrente</div>
                <div className="xp">se repete</div>
              </button>
            </div>
          </div>

          {/* One-time: deadline */}
          {!recurring && (
            <div className="field" style={{ marginBottom: 0 }}>
              <label>Prazo</label>
              <div className="cat-row">
                {['Hoje','Amanhã','Esta semana','Sem prazo'].map((d) => (
                  <button key={d} className={`cat-pill ${deadline === d ? 'on' : ''}`} onClick={() => setDeadline(d)}>{d}</button>
                ))}
              </div>
            </div>
          )}

          {/* Recurring: day picker */}
          {recurring && (
            <div className="field" style={{ marginBottom: 0 }}>
              <label>Dias da semana</label>
              <div className="cat-row" style={{ marginBottom: 10 }}>
                <button className={`cat-pill ${isAllDays ? 'on' : ''}`}      onClick={() => setPreset('all')}>↻ Todo dia</button>
                <button className={`cat-pill ${isWeekdaysPre ? 'on' : ''}`}  onClick={() => setPreset('weekdays')}>↻ Dias úteis</button>
                <button className={`cat-pill ${isWeekendPre ? 'on' : ''}`}   onClick={() => setPreset('weekend')}>↻ Fim de semana</button>
              </div>
              <div className="day-picker">
                {DAYS.map((d) => (
                  <button key={d.key} className={`day-btn ${selectedDays.includes(d.key) ? 'on' : ''}`} onClick={() => toggleDay(d.key)}>
                    {d.label}
                  </button>
                ))}
              </div>
              {selectedDays.length > 0 && (
                <div className="rec-preview">
                  ↻ {recurrenceLabel(computeRec(selectedDays))}
                </div>
              )}
            </div>
          )}
        </div>

        <div className="modal-foot">
          <div className="total">
            <div>
              <div className="lab">Recompensa</div>
              <div className="xp-pill">+{xp} XP</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn ghost" onClick={onClose}>Cancelar</button>
            <button className="btn gold" onClick={submit} disabled={!title.trim() || (recurring && selectedDays.length === 0)}>
              <I.bolt /> Forjar missão
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

window.Forge = Forge;
