// SATMELI — Crear / editar búsqueda, con preview en vivo.

function Field({ label, hint, children, icon }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font)', fontSize: 13, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.01em' }}>
        {icon && <span style={{ color: 'var(--muted)' }}><Icon name={icon} size={15} /></span>}
        {label}
        {hint && <span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, fontWeight: 400, color: 'var(--muted-3)', letterSpacing: 0 }}>{hint}</span>}
      </span>
      {children}
    </label>
  );
}

const inputStyle = {
  fontFamily: 'var(--font)', fontSize: 15, color: 'var(--ink)', background: 'var(--surface)',
  border: '1.5px solid var(--line-strong)', borderRadius: 'var(--r-md)', padding: '12px 14px',
  width: '100%', boxSizing: 'border-box', outline: 'none', letterSpacing: '-0.01em',
  transition: 'border-color 160ms var(--ease), box-shadow 160ms var(--ease)',
};

function TextInput(props) {
  return <input {...props} className="sat-input" style={{ ...inputStyle, ...(props.style || {}) }} />;
}

function PriceInput({ value, onChange, placeholder }) {
  return (
    <div style={{ position: 'relative' }}>
      <span style={{ position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', fontFamily: 'var(--mono)', fontSize: 14, color: 'var(--muted)' }}>$</span>
      <input type="text" inputMode="numeric" value={value ? Number(value).toLocaleString('es-AR') : ''} placeholder={placeholder}
        onChange={(e) => onChange(Number(e.target.value.replace(/\D/g, '')) || 0)}
        className="sat-input" style={{ ...inputStyle, paddingLeft: 28, fontFamily: 'var(--mono)', fontSize: 14 }} />
    </div>
  );
}

function CatPills({ value, onChange }) {
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
      {Object.entries(SAT_CATS).map(([k, c]) => {
        const active = value === k;
        return (
          <button key={k} type="button" onClick={() => onChange(k)}
            style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '9px 13px', borderRadius: 'var(--r-pill)',
              border: `1.5px solid ${active ? c.tint : 'var(--line-strong)'}`, cursor: 'pointer',
              background: active ? `color-mix(in srgb, ${c.tint} 13%, var(--surface))` : 'var(--surface)',
              color: active ? c.tint : 'var(--muted-2)', fontFamily: 'var(--font)', fontSize: 13, fontWeight: 600,
              letterSpacing: '-0.01em', transition: 'all 150ms var(--ease)' }}>
            <Icon name={c.icon} size={15} stroke={1.9} />{c.label}
          </button>
        );
      })}
    </div>
  );
}

function SelectBox({ value, onChange, options }) {
  return (
    <div style={{ position: 'relative' }}>
      <select value={value} onChange={(e) => onChange(e.target.value)}
        style={{ ...inputStyle, appearance: 'none', WebkitAppearance: 'none', cursor: 'pointer', paddingRight: 38 }}>
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
      <span style={{ position: 'absolute', right: 13, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none', color: 'var(--muted)' }}>
        <Icon name="chevDown" size={17} />
      </span>
    </div>
  );
}

const LOCATIONS = ['Argentina', 'CABA', 'GBA Norte', 'GBA Sur', 'GBA Oeste', 'Córdoba', 'Rosario', 'Mendoza', 'La Plata'];
const FREQS = [
  { value: '5m', label: '5 min' }, { value: '15m', label: '15 min' }, { value: '1h', label: '1 hora' },
  { value: '6h', label: '6 horas' }, { value: '1d', label: '1 día' },
];

function CreateSearch({ initial, mode, onCancel, onSave }) {
  const editing = !!initial;
  const [f, setF] = React.useState(() => initial ? { matchMode: 'exacta', ...initial } : {
    term: '', cat: 'tech', condition: 'cualquiera', priceMin: 0, priceMax: 0,
    location: 'Argentina', freq: '1d', notify: true, matchMode: 'exacta',
  });
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const desktop = mode === 'desktop';
  const valid = f.term.trim().length > 1;

  const previewSearch = { id: 'sx', ...f, active: true, matches: 0, lastCheck: 0, createdAt: 0, activity: [0,0,0,0,0,0,0,0,0,0,0,0,0,0] };

  const form = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <Field label="¿Qué estás buscando?" icon="search" hint="el término que vas a vigilar">
        <TextInput value={f.term} placeholder="Ej: iPhone 15 Pro usado" onChange={(e) => set('term', e.target.value)} autoFocus={!editing} />
      </Field>

      <Field label="Coincidencia" icon="filter" hint="qué tan estricto es el match">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Segmented full value={f.matchMode || 'exacta'} onChange={(v) => set('matchMode', v)}
            options={[{ value: 'exacta', label: 'Exacta' }, { value: 'amplia', label: 'Amplia' }]} />
          <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', lineHeight: 1.45 }}>
            {(f.matchMode || 'exacta') === 'exacta'
              ? 'Solo productos cuyo nombre contenga todas las palabras del término. Máxima precisión.'
              : 'Incluye productos parecidos de la misma marca o categoría. Más cobertura, menos precisión.'}
          </div>
        </div>
      </Field>

      <Field label="Rango de precio" icon="tag" hint="dejá en blanco para sin tope">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 10, alignItems: 'center' }}>
          <PriceInput value={f.priceMin} onChange={(v) => set('priceMin', v)} placeholder="mínimo" />
          <span style={{ fontFamily: 'var(--mono)', fontSize: 13, color: 'var(--muted-3)' }}>—</span>
          <PriceInput value={f.priceMax} onChange={(v) => set('priceMax', v)} placeholder="máximo" />
        </div>
      </Field>

      <Field label="Condición" icon="sliders">
        <Segmented full value={f.condition} onChange={(v) => set('condition', v)}
          options={[{ value: 'nuevo', label: 'Nuevo' }, { value: 'usado', label: 'Usado' }, { value: 'cualquiera', label: 'Cualquiera' }]} />
      </Field>

      <Field label="Categoría" icon="grid" hint="opcional, afina los resultados">
        <CatPills value={f.cat} onChange={(v) => set('cat', v)} />
      </Field>

      <div style={{ display: 'grid', gridTemplateColumns: desktop ? '1fr 1fr' : '1fr', gap: 16 }}>
        <Field label="Ubicación" icon="pin">
          <SelectBox value={f.location} onChange={(v) => set('location', v)} options={LOCATIONS} />
        </Field>
        <Field label="Frecuencia de chequeo" icon="clock" hint="cada cuánto revisa MELI">
          <Segmented full size="sm" value={f.freq} onChange={(v) => set('freq', v)} options={FREQS} />
        </Field>
      </div>

      {/* notificaciones */}
      <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 4 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 14px' }}>
          <span style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', background: 'var(--surface-2)', color: 'var(--ink)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name="bell" size={19} /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: 'var(--font)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>Notificarme al instante</div>
            <div style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)', marginTop: 2 }}>push + Telegram cuando haya match</div>
          </div>
          <Toggle on={f.notify} onChange={(v) => set('notify', v)} />
        </div>
      </div>
    </div>
  );

  const preview = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Eyebrow>Vista previa</Eyebrow>
      <CardMonitor s={previewSearch} onOpen={() => {}} onToggle={() => {}} />
      <div style={{ background: 'var(--surface-2)', borderRadius: 'var(--r-md)', padding: 14, border: '1px solid var(--line)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, color: 'var(--muted)' }}>
          <Icon name="send" size={14} /><span style={{ fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '0.08em' }}>ASÍ TE AVISA EL BOT</span>
        </div>
        <div style={{ fontFamily: 'var(--font)', fontSize: 13.5, color: 'var(--ink)', lineHeight: 1.5 }}>
          🔔 Nuevo match para <b>{f.term || 'tu búsqueda'}</b><br />
          <span style={{ color: 'var(--muted)' }}>{condLabel(f.condition)} · {f.location} · {priceRangeLabel(previewSearch)}</span>
        </div>
      </div>
    </div>
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <button type="button" onClick={onCancel} className="sat-iconbtn"
          style={{ width: 38, height: 38, borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', background: 'var(--surface)',
            color: 'var(--ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
          <Icon name="chevL" size={19} />
        </button>
        <div style={{ flex: 1 }}>
          <Eyebrow style={{ marginBottom: 4 }}>{editing ? 'Editar centinela' : 'Nuevo centinela'}</Eyebrow>
          <h1 style={{ fontFamily: 'var(--font)', fontSize: desktop ? 27 : 23, fontWeight: 700, letterSpacing: '-0.03em', color: 'var(--ink)', margin: 0, lineHeight: 1.05 }}>
            {editing ? 'Editar búsqueda' : 'Crear búsqueda'}
          </h1>
        </div>
      </div>

      {desktop ? (
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 28, alignItems: 'start' }}>
          {form}
          <div style={{ position: 'sticky', top: 0 }}>{preview}</div>
        </div>
      ) : (
        <>
          {form}
          {preview}
        </>
      )}

      {/* barra de guardar */}
      <div style={{ display: 'flex', gap: 10, position: 'sticky', bottom: 0, zIndex: 4,
        margin: desktop ? '4px -32px -48px' : '4px -16px -24px', padding: desktop ? '16px 32px 24px' : '14px 16px 24px',
        background: 'var(--bg-bar)', backdropFilter: 'blur(10px)', WebkitBackdropFilter: 'blur(10px)', borderTop: '1px solid var(--line)' }}>
        <Btn variant="ghost" onClick={onCancel} style={{ flex: desktop ? '0 0 auto' : 1 }}>Cancelar</Btn>
        <Btn variant="primary" size="lg" icon={editing ? 'check' : 'radar'} disabled={!valid} full={!desktop}
          onClick={() => valid && onSave({ ...previewSearch, id: initial ? initial.id : 's' + Date.now(), matches: initial ? initial.matches : 0,
            lastCheck: initial ? initial.lastCheck : 0, createdAt: initial ? initial.createdAt : 0,
            activity: initial ? initial.activity : previewSearch.activity })}
          style={{ flex: desktop ? '0 0 auto' : 2, opacity: valid ? 1 : 0.5, cursor: valid ? 'pointer' : 'not-allowed', minWidth: desktop ? 220 : undefined }}>
          {editing ? 'Guardar cambios' : 'Activar centinela'}
        </Btn>
      </div>
    </div>
  );
}

Object.assign(window, { CreateSearch });
