// ItemSettings.jsx — TaskSettings + RoutineSettings modals (mobile + desktop)
// Design source: easylife-components.jsx (TaskSettings line 903, RoutineSettings line 617)
const {
  useState: useIsState,
  useEffect: useIsEffect,
  useRef: useIsRef,
} = React;

const IS_PRIORITY = [
  { key: 'do',       label: 'Gjør først', icon: 'ti-flame',      color: '#34d399' },
  { key: 'schedule', label: 'Planlegg',   icon: 'ti-calendar',   color: '#fbbf24' },
  { key: 'delegate', label: 'Deleger',    icon: 'ti-user-share', color: '#38bdf8' },
  { key: 'later',    label: 'Senere',     icon: 'ti-moon',       color: '#94a3b8' },
];

function isYMD(d) {
  if (!d) return '';
  if (typeof d === 'string') return d.slice(0, 10);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

// ── Shared modal shell (centers on desktop, bottom-sheet on mobile) ──
function IsModalShell({ isOpen, onClose, title, variant, children }) {
  useIsEffect(() => {
    if (!isOpen) return;
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const isMobile = variant === 'mobile';

  return ReactDOM.createPortal(
    <div className={`is-wrap${isMobile ? ' is-mobile' : ''}`} onClick={onClose}>
      <div className={`is-card${isMobile ? ' is-card-mob' : ''}`} onClick={e => e.stopPropagation()}>
        {isMobile && <div className="is-handle" />}
        <div className="is-head">
          <span className="is-title">{title}</span>
          <button type="button" className="is-close" onClick={onClose} aria-label="Lukk">
            <i className="ti ti-x"></i>
          </button>
        </div>
        <div className="is-body">{children}</div>
      </div>
    </div>,
    document.body
  );
}

// ──────────────────────────────────────────────────────────────
// TaskSettings — edit a task: title, date, priority, big-win, category, delete
// ──────────────────────────────────────────────────────────────
function TaskSettings({ isOpen, task, onClose, onSave, onDelete, variant = 'desktop' }) {
  const [name, setName] = useIsState('');
  const [dueDate, setDueDate] = useIsState('');
  const [priority, setPriority] = useIsState('do');
  const [bigWin, setBigWin] = useIsState(false);
  const [category, setCategory] = useIsState('Personal');

  useIsEffect(() => {
    if (!isOpen || !task) return;
    setName(task.name || task.title || '');
    setDueDate(isYMD(task.due_date || task.due_at || ''));
    setPriority(task.v2_priority || 'do');
    setBigWin(!!task.is_big_win);
    const c = String(task.category || 'personal').toLowerCase();
    setCategory(c === 'work' ? 'Work' : 'Personal');
  }, [isOpen, task]);

  if (!isOpen || !task) return null;

  function handleSave() {
    onSave({
      id: task.id,
      name: name.trim() || task.name || '(uten tittel)',
      due_date: dueDate || null,
      v2_priority: priority,
      is_big_win: bigWin,
      category: category.toLowerCase(),
    });
    onClose();
  }

  return (
    <IsModalShell isOpen={isOpen} onClose={onClose} title="Rediger oppgave" variant={variant}>
      <label className="is-field">
        <span className="is-label">Tittel</span>
        <input
          type="text"
          className="is-input"
          value={name}
          onChange={e => setName(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') handleSave(); }}
        />
      </label>

      <label className="is-field">
        <span className="is-label">Forfallsdato</span>
        <input
          type="date"
          className="is-input"
          value={dueDate}
          onChange={e => setDueDate(e.target.value)}
        />
      </label>

      <div className="is-field">
        <span className="is-label">Prioritet</span>
        <div className="is-prio-grid">
          {IS_PRIORITY.map(p => (
            <button
              key={p.key}
              type="button"
              className={`is-prio-btn${priority === p.key ? ' active' : ''}`}
              onClick={() => setPriority(p.key)}
              style={priority === p.key ? {
                borderColor: p.color, color: p.color, background: `${p.color}1f`,
              } : null}
            >
              <i className={`ti ${p.icon}`}></i>
              <span>{p.label}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="is-field">
        <span className="is-label">Kategori</span>
        <div className="is-cat-row">
          {['Work', 'Personal'].map(c => (
            <button
              key={c}
              type="button"
              className={`is-cat-btn${category === c ? ' active' : ''}`}
              onClick={() => setCategory(c)}
            >
              <i className={`ti ${c === 'Work' ? 'ti-briefcase' : 'ti-home'}`}></i>
              <span>{c === 'Work' ? 'Jobb' : 'Privat'}</span>
            </button>
          ))}
        </div>
      </div>

      <div
        className="is-field is-toggle-row"
        onClick={() => setBigWin(v => !v)}
        role="button"
        tabIndex={0}
      >
        <i
          className={`ti ${bigWin ? 'ti-star-filled' : 'ti-star'}`}
          style={{ color: bigWin ? 'var(--amber-ink, #f59e0b)' : 'var(--mut)', fontSize: 16 }}
        ></i>
        <span className="is-label" style={{ flex: 1, marginBottom: 0 }}>Markér som stor seier</span>
        <span className={`is-toggle${bigWin ? ' on' : ''}`} aria-hidden="true" />
      </div>

      <div className="is-actions">
        <button
          type="button"
          className="is-btn-del"
          onClick={() => { if (confirm('Slette denne oppgaven?')) { onDelete(task.id); onClose(); } }}
        >
          <i className="ti ti-trash"></i>
          <span>Slett</span>
        </button>
        <div style={{ flex: 1 }} />
        <button type="button" className="is-btn-cancel" onClick={onClose}>Avbryt</button>
        <button type="button" className="is-btn-save" onClick={handleSave}>Lagre</button>
      </div>
    </IsModalShell>
  );
}

// ──────────────────────────────────────────────────────────────
// RoutineSettings — create/edit a routine: name, frequency, days, category
// ──────────────────────────────────────────────────────────────
const RS_DAY_LABELS = ['M', 'T', 'O', 'T', 'F', 'L', 'S'];
const RS_DAY_KEYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];

function RoutineSettings({ isOpen, routine, onClose, onSave, onDelete, variant = 'desktop' }) {
  const isNew = !routine?.id;
  const [name, setName] = useIsState('');
  const [frequency, setFrequency] = useIsState('daily');
  const [days, setDays] = useIsState([]);
  const [category, setCategory] = useIsState('Personal');

  useIsEffect(() => {
    if (!isOpen) return;
    setName(routine?.name || '');
    const fq = routine?.frequency || 'daily';
    setFrequency(fq === 'specific_days' || fq === 'weekly' ? 'weekly' : 'daily');
    setDays(Array.isArray(routine?.days) ? routine.days : []);
    const c = String(routine?.work_personal_category || routine?.category || 'personal').toLowerCase();
    setCategory(c === 'work' ? 'Work' : 'Personal');
  }, [isOpen, routine]);

  if (!isOpen) return null;

  function toggleDay(d) {
    setDays(prev => prev.includes(d) ? prev.filter(x => x !== d) : [...prev, d]);
  }

  function handleSave() {
    const trimmed = name.trim();
    if (!trimmed) return;
    onSave({
      id: routine?.id,
      name: trimmed,
      frequency: frequency === 'weekly' ? 'specific_days' : 'daily',
      days: frequency === 'weekly' ? days : null,
      work_personal_category: category,
    });
    onClose();
  }

  return (
    <IsModalShell
      isOpen={isOpen}
      onClose={onClose}
      title={isNew ? 'Ny rutine' : 'Rediger rutine'}
      variant={variant}
    >
      <label className="is-field">
        <span className="is-label">Navn</span>
        <input
          type="text"
          className="is-input"
          value={name}
          onChange={e => setName(e.target.value)}
          placeholder="F.eks. Morgenmeditasjon"
          onKeyDown={e => { if (e.key === 'Enter') handleSave(); }}
        />
      </label>

      <div className="is-field">
        <span className="is-label">Frekvens</span>
        <div className="is-cat-row">
          {[
            { k: 'daily',  l: 'Daglig' },
            { k: 'weekly', l: 'Valgte dager' },
          ].map(o => (
            <button
              key={o.k}
              type="button"
              className={`is-cat-btn${frequency === o.k ? ' active' : ''}`}
              onClick={() => setFrequency(o.k)}
            >
              <span>{o.l}</span>
            </button>
          ))}
        </div>
      </div>

      {frequency === 'weekly' && (
        <div className="is-field">
          <span className="is-label">Dager</span>
          <div className="is-day-row">
            {RS_DAY_LABELS.map((lbl, i) => {
              const k = RS_DAY_KEYS[i];
              const active = days.includes(k);
              return (
                <button
                  key={k}
                  type="button"
                  className={`is-day-btn${active ? ' active' : ''}`}
                  onClick={() => toggleDay(k)}
                  aria-pressed={active}
                >{lbl}</button>
              );
            })}
          </div>
        </div>
      )}

      <div className="is-field">
        <span className="is-label">Kategori</span>
        <div className="is-cat-row">
          {['Work', 'Personal'].map(c => (
            <button
              key={c}
              type="button"
              className={`is-cat-btn${category === c ? ' active' : ''}`}
              onClick={() => setCategory(c)}
            >
              <i className={`ti ${c === 'Work' ? 'ti-briefcase' : 'ti-home'}`}></i>
              <span>{c === 'Work' ? 'Jobb' : 'Privat'}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="is-actions">
        {!isNew && (
          <button
            type="button"
            className="is-btn-del"
            onClick={() => {
              if (confirm('Slette denne rutinen? Historikken beholdes.')) {
                onDelete(routine.id);
                onClose();
              }
            }}
          >
            <i className="ti ti-trash"></i>
            <span>Slett</span>
          </button>
        )}
        <div style={{ flex: 1 }} />
        <button type="button" className="is-btn-cancel" onClick={onClose}>Avbryt</button>
        <button
          type="button"
          className="is-btn-save"
          onClick={handleSave}
          disabled={!name.trim()}
          style={!name.trim() ? { opacity: 0.45, cursor: 'not-allowed' } : null}
        >Lagre</button>
      </div>
    </IsModalShell>
  );
}
