// quotes.jsx — Personalized Quotes manager (premium). Slides up over the app like
// the Premium sheet. Lets the user choose what surfaces during sessions (Eme /
// theirs / both) and create, edit, and delete their own quotes. Mirrors the
// minimalist settings language: quiet cards, soft accents, no clutter.

// Resolve the pool of strings shown during a session from the source preference.
// Free users always get the curated Eme phrases; personalization is premium.
function resolveQuotePool({ system, custom, source, isPremium }) {
  const sys = (system || []).filter(Boolean);
  const mine = (custom || []).map((q) => (q && q.text ? q.text : q)).filter(Boolean);
  if (!isPremium) return sys;
  if (source === 'custom') return mine.length ? mine : sys;
  if (source === 'mix') return mine.length ? sys.concat(mine) : sys;
  return sys;
}

function QuoteSourceSeg({ value, onChange, accent, th, t }) {
  const opts = [
    { k: 'system', label: t('qsrc_system'), sub: t('qsrc_system_sub') },
    { k: 'mix',    label: t('qsrc_mix'),    sub: t('qsrc_mix_sub') },
    { k: 'custom', label: t('qsrc_custom'), sub: t('qsrc_custom_sub') },
  ];
  const active = opts.find((o) => o.k === value) || opts[0];
  return (
    <div>
      <div style={{ display: 'flex', gap: 6, padding: 5, borderRadius: 16, background: th.surface, border: '1px solid ' + th.border }}>
        {opts.map((o) => {
          const on = value === o.k;
          return (
            <button key={o.k} onClick={() => onChange(o.k)} style={{
              flex: 1, padding: '11px 6px', borderRadius: 12, border: 'none', cursor: 'pointer', fontFamily: 'inherit',
              background: on ? `linear-gradient(135deg,${accent[0]},${accent[1]})` : 'transparent',
              color: on ? '#fff' : th.dim, fontSize: 14, fontWeight: on ? 500 : 400,
              boxShadow: on ? `0 6px 18px ${accent[0]}44` : 'none', transition: 'background .2s, color .2s, box-shadow .2s',
            }}>{o.label}</button>
          );
        })}
      </div>
      <div style={{ fontSize: 12.5, color: th.faint, marginTop: 10, textAlign: 'center', minHeight: 17, fontWeight: 300 }}>{active.sub}</div>
    </div>
  );
}

function QuoteItem({ q, accent, th, t, dir, onSave, onDelete }) {
  const [editing, setEditing] = React.useState(false);
  const [val, setVal] = React.useState(q.text);
  const commit = () => { const v = val.trim(); if (v && v !== q.text) onSave(q.id, v); setEditing(false); };
  if (editing) {
    return (
      <div style={{ padding: 12, borderRadius: 16, background: th.surface2, border: '1px solid ' + accent[0] + '55' }}>
        <textarea autoFocus value={val} maxLength={200} rows={2}
          onChange={(e) => setVal(e.target.value)}
          style={{ width: '100%', resize: 'none', padding: '10px 12px', borderRadius: 12, fontSize: 15, lineHeight: 1.5,
            fontFamily: 'inherit', background: th.surface, border: '1px solid ' + th.border2, color: th.text, outline: 'none' }} />
        <div style={{ display: 'flex', gap: 8, marginTop: 10, justifyContent: 'flex-end' }}>
          <button onClick={() => { setVal(q.text); setEditing(false); }} style={{ padding: '8px 16px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, border: '1px solid ' + th.border2, background: 'transparent', color: th.text }}>{t('cancel')}</button>
          <button onClick={commit} style={{ padding: '8px 18px', borderRadius: 11, cursor: 'pointer', fontFamily: 'inherit', fontSize: 13.5, border: 'none', background: `linear-gradient(135deg,${accent[0]},${accent[1]})`, color: '#fff', fontWeight: 500 }}>{t('save')}</button>
        </div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, padding: '13px 14px', borderRadius: 16, background: th.surface, border: '1px solid ' + th.border }}>
      <span style={{ color: accent[0], fontSize: 22, lineHeight: 1, fontWeight: 300, opacity: .7, marginTop: -2 }}>“</span>
      <button onClick={() => { setVal(q.text); setEditing(true); }} style={{
        flex: 1, minWidth: 0, textAlign: dir === 'rtl' ? 'right' : 'left', background: 'none', border: 'none', cursor: 'pointer',
        font: 'inherit', color: th.text, fontSize: 15, fontWeight: 300, lineHeight: 1.5, padding: 0,
      }}>{q.text}</button>
      <button onClick={() => onDelete(q.id)} aria-label={t('reset')} style={{
        flexShrink: 0, width: 28, height: 28, borderRadius: '50%', cursor: 'pointer',
        background: th.surface2, border: '1px solid ' + th.border, color: th.faint,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}><IconClose size={13} /></button>
    </div>
  );
}

function QuotesManager({ th, accent, level, quotes, source, onClose, onAdd, onUpdate, onDelete, onSetSource, onToast }) {
  const { t, dir } = useI18n();
  const lv = level || LEVELS[1];
  const [draft, setDraft] = React.useState('');
  const list = quotes || [];
  const add = () => {
    const v = draft.trim();
    if (!v) return;
    onAdd(v); setDraft(''); onToast(t('toast_quote_added'));
    haptic(12, true);
  };
  const del = (id) => { onDelete(id); onToast(t('toast_quote_deleted')); };
  const save = (id, text) => { onUpdate(id, text); onToast(t('toast_quote_saved')); };

  return (
    <div className="prem-overlay" dir={dir}>
      <div className="prem-backdrop" onClick={onClose} />
      <div className="prem-sheet" style={{ background: th.sheet, borderColor: th.border2 }}>
        {/* grab handle + close */}
        <div style={{ position: 'relative', flexShrink: 0, padding: '12px 16px 0' }}>
          <div style={{ width: 38, height: 4, borderRadius: 99, background: th.ghost, margin: '0 auto' }} />
          <button onClick={onClose} aria-label={t('np_close')} style={{
            position: 'absolute', top: 12, insetInlineEnd: 14, width: 34, height: 34, borderRadius: '50%',
            background: th.surface2, border: '1px solid ' + th.border, color: th.text, cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}><IconClose size={16} /></button>
        </div>

        <div className="scroll-area" style={{ flex: 1, padding: '4px 22px 28px' }}>
          {/* hero */}
          <div className="prem-fade" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', paddingTop: 10 }}>
            <LevelRing size={78} colors={[lv.left, lv.right]} breathe={false}>
              <span style={{ color: lv.glow, display: 'flex', filter: `drop-shadow(0 0 8px ${lv.glow}cc)` }}><IconQuote size={26} /></span>
            </LevelRing>
            <div style={{ fontSize: 24, fontWeight: 200, color: th.text, marginTop: 16, letterSpacing: .2 }}>{t('quotes_manage_title')}</div>
            <div style={{ fontSize: 13.5, color: th.dim, fontWeight: 300, marginTop: 8, maxWidth: 280, lineHeight: 1.5 }}>{t('quotes_manage_intro')}</div>
          </div>

          {/* source */}
          <SectionTitle th={th}>{t('quote_source')}</SectionTitle>
          <QuoteSourceSeg value={source} onChange={onSetSource} accent={accent} th={th} t={t} />

          {/* your quotes */}
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', margin: '26px 2px 12px' }}>
            <div style={{ fontSize: 11, letterSpacing: 2.4, color: th.faint, fontWeight: 500, textTransform: 'uppercase' }}>{t('your_quotes')}</div>
            <div style={{ fontSize: 12, color: th.ghost }}>{t('quote_count', { n: list.length })}</div>
          </div>

          {/* composer */}
          <div style={{ borderRadius: 16, background: th.surface, border: '1px solid ' + th.border, padding: 12 }}>
            <textarea value={draft} maxLength={200} rows={2} placeholder={t('quote_placeholder')}
              onChange={(e) => setDraft(e.target.value)}
              style={{ width: '100%', resize: 'none', padding: '10px 12px', borderRadius: 12, fontSize: 15, lineHeight: 1.5,
                fontFamily: 'inherit', background: th.surface2, border: '1px solid ' + th.border2, color: th.text, outline: 'none' }} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 10 }}>
              <button onClick={add} disabled={!draft.trim()} style={{
                padding: '10px 22px', borderRadius: 12, cursor: draft.trim() ? 'pointer' : 'default', fontFamily: 'inherit', fontSize: 14, fontWeight: 500,
                border: 'none', color: '#fff', opacity: draft.trim() ? 1 : .4,
                background: `linear-gradient(135deg,${accent[0]},${accent[1]})`, boxShadow: draft.trim() ? `0 6px 18px ${accent[0]}44` : 'none',
                display: 'flex', alignItems: 'center', gap: 7,
              }}><IconSparkle size={15} />{t('quote_add_cta')}</button>
            </div>
          </div>

          {/* list */}
          {list.length === 0 ? (
            <div style={{ marginTop: 14, padding: '22px 18px', borderRadius: 16, border: '1px dashed ' + th.border2,
              textAlign: 'center', fontSize: 13.5, color: th.faint, fontWeight: 300, lineHeight: 1.5 }}>{t('no_custom_quotes')}</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
              {list.map((q) => (
                <QuoteItem key={q.id} q={q} accent={accent} th={th} t={t} dir={dir} onSave={save} onDelete={del} />
              ))}
            </div>
          )}

          {source === 'custom' && list.length === 0 && (
            <div style={{ marginTop: 14, fontSize: 12.5, color: accent[0], textAlign: 'center', fontWeight: 300 }}>{t('quote_empty_hint')}</div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { QuotesManager, resolveQuotePool });

  