// Scheduling — recurring search-run config (UI + store)
// Store: scheduled-runs array per profile in localStorage.
// Shape per run: { id, profileId, query{businessType,location,contact,extras,amount}, frequency, time, weekday, dayOfMonth, autoPush, active, createdAt }

const SCHED_STORE_KEY = 'ls.scheduledRuns.v1';

function loadSchedules() {
  try {
    const raw = localStorage.getItem(SCHED_STORE_KEY);
    if (!raw) return seedSchedules();
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed : seedSchedules();
  } catch { return seedSchedules(); }
}
function saveSchedules(list) {
  try { localStorage.setItem(SCHED_STORE_KEY, JSON.stringify(list)); } catch {}
}

// Seed: 1 demo scheduled run on Faltschachtel profile so users see the pattern
function seedSchedules() {
  const seed = [{
    id: 'sched-seed-1',
    profileId: 'falt',
    query: {
      businessType: 'Faltschachtelhersteller',
      location: 'Nordrhein-Westfalen',
      contact: 'Vertriebsleiter, Einkäufer',
      extras: '50–250 MA · Eigene Produktion',
      amount: 40,
    },
    frequency: 'weekly',
    time: '08:00',
    weekday: 1, // Mon
    dayOfMonth: 1,
    autoPush: true,
    active: true,
    createdAt: Date.now() - 1000*60*60*24*9,
  }];
  saveSchedules(seed);
  return seed;
}

function useSchedules() {
  const [list, _set] = useState(loadSchedules);
  const set = (next) => {
    const value = typeof next === 'function' ? next(list) : next;
    _set(value);
    saveSchedules(value);
  };
  return [list, set];
}

// --- Next-run computation ------------------------------------------------
function nextRunAt(sched, from = new Date()) {
  const [h, m] = (sched.time || '08:00').split(':').map(Number);
  const d = new Date(from);
  if (sched.frequency === 'daily') {
    d.setHours(h, m, 0, 0);
    if (d <= from) d.setDate(d.getDate() + 1);
    return d;
  }
  if (sched.frequency === 'weekly') {
    // weekday: 0=Sun..6=Sat (our UI uses 1=Mon..7=Sun, normalize)
    const targetJsDay = (sched.weekday % 7); // 7(Sun) → 0
    const diff = (targetJsDay - from.getDay() + 7) % 7;
    d.setDate(from.getDate() + diff);
    d.setHours(h, m, 0, 0);
    if (d <= from) d.setDate(d.getDate() + 7);
    return d;
  }
  if (sched.frequency === 'monthly') {
    d.setDate(Math.min(sched.dayOfMonth || 1, 28));
    d.setHours(h, m, 0, 0);
    if (d <= from) d.setMonth(d.getMonth() + 1);
    return d;
  }
  return null;
}

function formatRelative(date, lang = 'de') {
  if (!date) return '';
  const now = new Date();
  const diffMs = date - now;
  const diffH = Math.round(diffMs / (1000 * 60 * 60));
  const diffD = Math.round(diffH / 24);
  const isEn = lang === 'en';
  if (diffMs < 0) return isEn ? 'overdue' : 'überfällig';
  if (diffH < 1) return isEn ? 'soon' : 'bald';
  if (diffH < 24) return isEn ? `in ${diffH} h` : `in ${diffH} h`;
  if (diffD === 1) return isEn ? 'tomorrow' : 'morgen';
  if (diffD < 7) return isEn ? `in ${diffD} days` : `in ${diffD} Tagen`;
  return date.toLocaleDateString(isEn ? 'en-US' : 'de-DE', { day: '2-digit', month: 'short' });
}

// --- Schedule config UI (used inside NewLeadsForm + RepeatRunModal) ------
function ScheduleConfig({ value, onChange, crmConnected }) {
  useLang();
  const f = value.frequency || 'once';

  const setF = (frequency) => onChange({ ...value, frequency });
  const setTime = (time) => onChange({ ...value, time });
  const setWeekday = (weekday) => onChange({ ...value, weekday });
  const setDOM = (dayOfMonth) => onChange({ ...value, dayOfMonth });
  const setAutoPush = (autoPush) => onChange({ ...value, autoPush });

  return (
    <div className="rounded-lg border border-line bg-[#FAFCFF] px-4 py-4">
      <div className="flex items-start gap-2 mb-3">
        <RepeatIcon size={14} className="text-[#3465E3] mt-[2px] flex-shrink-0"/>
        <div className="flex-1 min-w-0">
          <div className="text-[13px] font-semibold text-ink leading-tight">{t('sched.section')}</div>
          <div className="text-[11.5px] text-ink-muted mt-0.5 leading-snug">{t('sched.sectionSub')}</div>
        </div>
      </div>

      {/* Frequency options */}
      <div className="grid grid-cols-2 gap-2">
        <FrequencyOption value="once"    label={t('sched.once')}    sub={t('sched.onceSub')}    selected={f==='once'}    onClick={() => setF('once')}/>
        <FrequencyOption value="daily"   label={t('sched.daily')}   sub={t('sched.dailySub')}   selected={f==='daily'}   onClick={() => setF('daily')}/>
        <FrequencyOption value="weekly"  label={t('sched.weekly')}  sub={t('sched.weeklySub')}  selected={f==='weekly'}  onClick={() => setF('weekly')}/>
        <FrequencyOption value="monthly" label={t('sched.monthly')} sub={t('sched.monthlySub')} selected={f==='monthly'} onClick={() => setF('monthly')}/>
      </div>

      {/* Recurrence details */}
      {f !== 'once' && (
        <div className="mt-3 pt-3 border-t border-[#E8ECF4] space-y-3">
          {f === 'weekly' && (
            <div>
              <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('sched.weekday')}</label>
              <div className="flex gap-1">
                {[1,2,3,4,5,6,7].map(d => {
                  const keys = ['mon','tue','wed','thu','fri','sat','sun'];
                  const sel = (value.weekday || 1) === d;
                  return (
                    <button key={d} type="button" onClick={() => setWeekday(d)}
                            className={`flex-1 h-8 rounded-md text-[12px] font-medium transition-colors ${
                              sel ? 'bg-[#3465E3] text-white' : 'bg-white border border-line text-ink-muted hover:text-ink'
                            }`}>
                      {t(`sched.day.${keys[d-1]}.short`)}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {f === 'monthly' && (
            <div>
              <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('sched.dayOfMonth')}</label>
              <input type="number" min={1} max={28}
                     value={value.dayOfMonth || 1}
                     onChange={(e) => setDOM(Math.max(1, Math.min(28, Number(e.target.value) || 1)))}
                     className="w-full h-9 px-3 rounded-md border border-line bg-white text-[13px] focus:outline-none focus:border-[#3465E3]"/>
              <div className="text-[10.5px] text-ink-soft mt-1">1–28 (vermeidet Monatsende-Probleme)</div>
            </div>
          )}

          <div>
            <label className="block text-[11.5px] text-ink-muted mb-1.5">{t('sched.time')}</label>
            <input type="time" value={value.time || '08:00'} onChange={(e) => setTime(e.target.value)}
                   className="w-full h-9 px-3 rounded-md border border-line bg-white text-[13px] focus:outline-none focus:border-[#3465E3]"/>
          </div>

          {/* Auto-push */}
          <div className="pt-2 border-t border-[#E8ECF4]">
            <label className={`flex items-start gap-2.5 cursor-pointer group ${!crmConnected ? 'opacity-60 cursor-not-allowed' : ''}`}>
              <div className="pt-[2px]">
                <div className={`w-9 h-5 rounded-full transition-colors relative ${
                  value.autoPush && crmConnected ? 'bg-[#3465E3]' : 'bg-gray-300'
                }`}>
                  <div className={`absolute top-0.5 w-4 h-4 rounded-full bg-white transition-transform ${
                    value.autoPush && crmConnected ? 'translate-x-[18px]' : 'translate-x-[2px]'
                  }`}/>
                </div>
                <input type="checkbox" className="sr-only"
                       checked={!!(value.autoPush && crmConnected)}
                       disabled={!crmConnected}
                       onChange={(e) => setAutoPush(e.target.checked)}/>
              </div>
              <div className="flex-1">
                <div className="text-[12.5px] font-medium text-ink leading-tight">{t('sched.autoPush')}</div>
                <div className="text-[11px] text-ink-muted mt-0.5 leading-snug">
                  {crmConnected ? t('sched.autoPushSub') : t('sched.autoPushNoCRM')}
                </div>
              </div>
            </label>
          </div>
        </div>
      )}
    </div>
  );
}

function FrequencyOption({ label, sub, selected, onClick }) {
  return (
    <button type="button" onClick={onClick}
            className={`text-left px-3 py-2 rounded-lg border-2 transition-all ${
              selected ? 'border-[#3465E3] bg-[#F4F7FD]/60' : 'border-line bg-white hover:border-[#C5D2EC]'
            }`}>
      <div className="flex items-center gap-2">
        <div className={`w-3.5 h-3.5 rounded-full border-2 flex items-center justify-center flex-shrink-0 ${
          selected ? 'border-[#3465E3] bg-[#3465E3]' : 'border-[#D5DDEA] bg-white'
        }`}>
          {selected && <div className="w-1 h-1 rounded-full bg-white"/>}
        </div>
        <div className="text-[12.5px] font-semibold text-ink">{label}</div>
      </div>
      <div className="text-[10.5px] text-ink-muted mt-0.5 ml-[22px]">{sub}</div>
    </button>
  );
}

// --- Scheduled Runs table (in profile-memory screen) --------------------
function ScheduledRunsSection({ profile, schedules, setSchedules, toast, crmConnected }) {
  const lang = useLang();
  const profileSchedules = (schedules || []).filter(s => s.profileId === profile.id);

  if (profileSchedules.length === 0) {
    return (
      <div className="mt-10">
        <div className="flex items-end justify-between mb-3">
          <div>
            <h2 className="text-[18px] font-semibold text-ink tracking-tight">{t('schedRuns.title')}</h2>
            <p className="text-[12px] text-ink-muted mt-0.5">{t('schedRuns.sub')}</p>
          </div>
        </div>
        <div className="bg-white border border-line border-dashed rounded-lg py-10 px-6 text-center">
          <div className="w-11 h-11 rounded-full bg-[#F4F7FD] flex items-center justify-center mx-auto mb-3">
            <RepeatIcon size={18} className="text-ink-soft"/>
          </div>
          <div className="text-[13.5px] font-medium text-ink">{t('schedRuns.empty.title')}</div>
          <div className="text-[12px] text-ink-muted mt-1 max-w-[420px] mx-auto">{t('schedRuns.empty.sub')}</div>
        </div>
      </div>
    );
  }

  const togglePause = (id) => {
    setSchedules(list => list.map(s => s.id === id ? { ...s, active: !s.active } : s));
    const target = schedules.find(s => s.id === id);
    if (target) toast?.push(t(target.active ? 'sched.toast.paused' : 'sched.toast.resumed'), 'positive');
  };
  const remove = (id) => {
    setSchedules(list => list.filter(s => s.id !== id));
    toast?.push(t('sched.toast.deleted'), 'negative');
  };

  const freqLabel = (s) => {
    const dayKeys = ['mon','tue','wed','thu','fri','sat','sun'];
    if (s.frequency === 'daily') return t('schedRuns.freq.daily', { time: s.time });
    if (s.frequency === 'weekly') return t('schedRuns.freq.weekly', {
      day: t(`sched.day.${dayKeys[(s.weekday||1) - 1]}`),
      time: s.time,
    });
    if (s.frequency === 'monthly') return t('schedRuns.freq.monthly', { day: s.dayOfMonth, time: s.time });
    return '—';
  };

  return (
    <div className="mt-10">
      <div className="flex items-end justify-between mb-3">
        <div>
          <h2 className="text-[18px] font-semibold text-ink tracking-tight">{t('schedRuns.title')}</h2>
          <p className="text-[12px] text-ink-muted mt-0.5">{t('schedRuns.sub')}</p>
        </div>
        <span className="text-[11px] text-ink-soft tabular-nums">
          {profileSchedules.filter(s => s.active).length} {t('schedRuns.count')}
        </span>
      </div>
      <div className="bg-white border border-line rounded-lg overflow-hidden">
        <table className="w-full text-[13px]">
          <thead>
            <tr className="text-left text-[11px] uppercase tracking-[0.06em] text-ink-muted" style={{background:'#EEF2FE'}}>
              <th className="px-5 py-2.5 font-medium">{t('schedRuns.col.frequency')}</th>
              <th className="px-3 py-2.5 font-medium">{t('schedRuns.col.params')}</th>
              <th className="px-3 py-2.5 font-medium text-right">{t('schedRuns.col.leads')}</th>
              <th className="px-3 py-2.5 font-medium">{t('schedRuns.col.crm')}</th>
              <th className="px-3 py-2.5 font-medium">{t('schedRuns.col.nextRun')}</th>
              <th className="px-5 py-2.5 font-medium text-right"></th>
            </tr>
          </thead>
          <tbody>
            {profileSchedules.map(s => {
              const next = s.active ? nextRunAt(s) : null;
              return (
                <tr key={s.id} className={`border-t border-line hover:bg-[#FAFCFF] transition-colors ${!s.active ? 'opacity-60' : ''}`}>
                  <td className="px-5 py-3.5">
                    <div className="flex items-center gap-2">
                      <div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${s.active ? 'bg-emerald-500' : 'bg-gray-400'}`}/>
                      <div className="text-[13px] text-ink font-medium">{freqLabel(s)}</div>
                    </div>
                    {!s.active && (
                      <div className="text-[10.5px] text-ink-soft uppercase tracking-[0.06em] mt-0.5 ml-4">
                        {t('schedRuns.status.paused')}
                      </div>
                    )}
                  </td>
                  <td className="px-3 py-3.5">
                    <div className="text-[12.5px] text-ink truncate max-w-[320px]">{s.query.businessType} · {s.query.location}</div>
                    <div className="text-[11px] text-ink-soft truncate max-w-[320px]">
                      {s.query.contact}{s.query.extras ? ` · ${s.query.extras}` : ''}
                    </div>
                  </td>
                  <td className="px-3 py-3.5 text-right">
                    <span className="text-[14px] font-semibold text-ink tabular-nums">{s.query.amount}</span>
                  </td>
                  <td className="px-3 py-3.5">
                    {s.autoPush && crmConnected ? (
                      <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] font-medium bg-emerald-50 text-emerald-700">
                        <BoltIcon size={9}/> {t('schedRuns.crm.yes')}
                      </span>
                    ) : (
                      <span className="text-[11.5px] text-ink-soft">{t('schedRuns.crm.no')}</span>
                    )}
                  </td>
                  <td className="px-3 py-3.5">
                    {next ? (
                      <div>
                        <div className="text-[12.5px] text-ink">{next.toLocaleDateString(lang === 'en' ? 'en-US' : 'de-DE', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit' })}</div>
                        <div className="text-[10.5px] text-ink-soft">{formatRelative(next, lang)}</div>
                      </div>
                    ) : (
                      <span className="text-[11.5px] text-ink-soft">—</span>
                    )}
                  </td>
                  <td className="px-5 py-3.5 text-right">
                    <div className="inline-flex items-center gap-1">
                      <button onClick={() => togglePause(s.id)}
                              className="px-2.5 h-7 rounded-md text-[11.5px] font-medium text-ink-muted hover:bg-gray-50 hover:text-ink transition-colors">
                        {s.active ? t('schedRuns.pause') : t('schedRuns.resume')}
                      </button>
                      <button onClick={() => remove(s.id)}
                              className="w-7 h-7 rounded-md flex items-center justify-center text-ink-soft hover:text-red-600 hover:bg-red-50 transition-colors"
                              title={t('schedRuns.delete')}>
                        <TrashIcon size={13}/>
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// --- Small icons --------------------------------------------------------
function RepeatIcon({ size = 14, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/>
    <polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/>
  </svg>;
}
function BoltIcon({ size = 12, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}><polygon points="13 2 3 14 12 14 11 22 21 10 12 10"/></svg>;
}
function TrashIcon({ size = 13, className = '' }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>
  </svg>;
}

Object.assign(window, {
  loadSchedules, saveSchedules, useSchedules, nextRunAt, formatRelative,
  ScheduleConfig, ScheduledRunsSection,
});
