// Form-heavy views: Agendar, People, Tasks, Alerts, Notes
const { useState, useMemo, useEffect, useRef } = React;

// --- Novo agendamento (with recurring + price) ------------------------------
function Agendar({ store, go }) {
  const { people, settings } = store.data;
  const [form, setForm] = useState({
    title: "", personId: people[0]?.id || "", date: TODAY_ISO, time: "10:00", duration: 60,
    type: "Mentoria", status: "agendado", location: "", notes: "", reminder: 30,
    price: settings.prices?.Mentoria || 0,
  });
  const [recurring, setRecurring] = useState({ on: false, frequency: "weekly", count: 4 });

  // Sync price when type changes (only if user hasn't manually overridden)
  const lastTypeRef = useRef(form.type);
  useEffect(() => {
    if (lastTypeRef.current !== form.type) {
      setForm(f => ({ ...f, price: settings.prices?.[form.type] ?? f.price }));
      lastTypeRef.current = form.type;
    }
  }, [form.type, settings.prices]);

  const conflict = useMemo(() => {
    return store.data.appointments.find(a => a.date === form.date && a.time === form.time);
  }, [form.date, form.time, store.data.appointments]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const submit = (e) => {
    e.preventDefault();
    if (!form.title) return;
    if (recurring.on) {
      const all = expandRecurring(form, recurring.frequency, recurring.count);
      store.addAppointments(all);
    } else {
      store.addAppointment(form);
    }
    go("hoje");
  };

  return (
    <div className="view-wrap">
      <div className="grid-form">
        <Panel title="Dados do agendamento">
          <form onSubmit={submit} className="form">
            <div className="form-grid">
              <Field label="Título" full><input value={form.title} onChange={e => set("title", e.target.value)} placeholder="Ex: Sessão de avaliação" required /></Field>
              <Field label="Pessoa">
                <select value={form.personId} onChange={e => set("personId", e.target.value)}>
                  <option value="">— sem pessoa —</option>
                  {people.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </Field>
              <Field label="Tipo">
                <select value={form.type} onChange={e => set("type", e.target.value)}>
                  {Object.keys(TYPE_META).map(t => <option key={t}>{t}</option>)}
                </select>
              </Field>
              <Field label="Data"><input type="date" value={form.date} onChange={e => set("date", e.target.value)} required /></Field>
              <Field label="Horário"><input type="time" value={form.time} onChange={e => set("time", e.target.value)} required /></Field>
              <Field label="Duração (min)"><input type="number" min="10" step="5" value={form.duration} onChange={e => set("duration", Number(e.target.value))} /></Field>
              <Field label="Status">
                <select value={form.status} onChange={e => set("status", e.target.value)}>
                  {Object.entries(STATUS_META).map(([k,v]) => <option key={k} value={k}>{v.label}</option>)}
                </select>
              </Field>
              <Field label="Valor (R$)" hint="0 para sessões gratuitas">
                <input type="number" min="0" step="10" value={form.price} onChange={e => set("price", Number(e.target.value))} />
              </Field>
              <Field label="Local / link" full hint="Cole um link de Meet, Zoom, ou descreva o endereço.">
                <input value={form.location} onChange={e => set("location", e.target.value)} placeholder="https://meet.google.com/..." />
              </Field>
              <Field label="Lembrete (min antes)">
                <select value={form.reminder} onChange={e => set("reminder", Number(e.target.value))}>
                  <option value={0}>Sem lembrete</option>
                  <option value={10}>10 minutos</option>
                  <option value={15}>15 minutos</option>
                  <option value={30}>30 minutos</option>
                  <option value={60}>1 hora</option>
                </select>
              </Field>
              <Field label="Observações" full>
                <textarea rows="3" value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="Notas internas, contexto, próximos passos..." />
              </Field>
            </div>

            <div className="recurring-block">
              <label className="recurring-toggle">
                <input type="checkbox" checked={recurring.on} onChange={e => setRecurring(r => ({ ...r, on: e.target.checked }))} />
                <Icon name="repeat" size={14} />
                <span>Repetir este agendamento</span>
              </label>
              {recurring.on && (
                <div className="recurring-options">
                  <select value={recurring.frequency} onChange={e => setRecurring(r => ({ ...r, frequency: e.target.value }))}>
                    <option value="weekly">toda semana</option>
                    <option value="biweekly">a cada 2 semanas</option>
                    <option value="monthly">todo mês</option>
                  </select>
                  <span className="dim small">por</span>
                  <input type="number" min="2" max="52" value={recurring.count} onChange={e => setRecurring(r => ({ ...r, count: Number(e.target.value) }))} className="small-input" />
                  <span className="dim small">ocorrências (cria {recurring.count} agendamentos)</span>
                </div>
              )}
            </div>

            <div className="form-foot">
              {conflict && <Pill tone="warn">Conflito: já existe "{conflict.title}" às {conflict.time}</Pill>}
              <div style={{ flex: 1 }} />
              <Button variant="ghost" onClick={() => go("dashboard")}>Cancelar</Button>
              <Button type="submit">{recurring.on ? `Salvar ${recurring.count} agendamentos` : "Salvar agendamento"}</Button>
            </div>
          </form>
        </Panel>

        <Panel title="Pré-visualização">
          <div className="preview-card">
            <Pill tone="accent">{form.type}</Pill>
            <div className="preview-title">{form.title || "Sem título"}</div>
            <div className="preview-meta">
              <div><span className="dim">Pessoa</span><span>{people.find(p => p.id === form.personId)?.name || "—"}</span></div>
              <div><span className="dim">Quando</span><span>{new Date(form.date + "T00:00:00").toLocaleDateString("pt-BR", { weekday:"short", day:"2-digit", month:"short" })} · {form.time}</span></div>
              <div><span className="dim">Duração</span><span>{form.duration} min</span></div>
              <div><span className="dim">Valor</span><span className="tabular">{form.price ? formatBRL(form.price) : "—"}</span></div>
              <div><span className="dim">Status</span><span>{STATUS_META[form.status].label}</span></div>
              <div><span className="dim">Lembrete</span><span>{form.reminder ? `${form.reminder} min antes` : "—"}</span></div>
              <div className="full"><span className="dim">Local</span><span className="ellipsis">{form.location || "—"}</span></div>
            </div>
            {form.notes && <div className="preview-notes">{form.notes}</div>}
          </div>

          {recurring.on && (
            <div className="info-block">
              <div className="info-title"><Icon name="repeat" size={12} /> Série recorrente</div>
              <div className="dim small">Será criada uma série de {recurring.count} agendamentos {recurring.frequency === "weekly" ? "semanais" : recurring.frequency === "biweekly" ? "quinzenais" : "mensais"} a partir de {new Date(form.date + "T00:00:00").toLocaleDateString("pt-BR")}.</div>
            </div>
          )}
        </Panel>
      </div>
    </div>
  );
}

// --- Pessoas (with CSV import + click-to-detail) ----------------------------
function PeopleView({ store, filters, openPerson }) {
  const { people, appointments } = store.data;
  const [form, setForm] = useState({ name: "", phone: "", email: "", tag: "Lead quente", source: "Instagram", note: "" });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const fileRef = useRef(null);

  const submit = (e) => {
    e.preventDefault();
    if (!form.name) return;
    store.addPerson(form);
    setForm({ name: "", phone: "", email: "", tag: "Lead quente", source: "Instagram", note: "" });
  };

  const onCSV = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const parsed = parseCSV(e.target.result);
      if (parsed.length === 0) { alert("Nenhum contato encontrado no CSV. Cabeçalhos esperados: name, phone, email, tag, source, note."); return; }
      if (confirm(`Importar ${parsed.length} contatos do CSV?`)) {
        store.addPeople(parsed);
      }
    };
    reader.readAsText(file);
  };

  const list = people.filter(p => filters.q ? (p.name + p.email + p.phone + p.note).toLowerCase().includes(filters.q.toLowerCase()) : true);

  return (
    <div className="view-wrap">
      <div className="grid-people">
        <Panel title="Contatos" right={
          <div style={{ display: "flex", gap: 6 }}>
            <Pill>{list.length} pessoas</Pill>
            <button className="btn btn-ghost small" onClick={() => fileRef.current?.click()}>
              <Icon name="upload" size={12} /> CSV
            </button>
            <input ref={fileRef} type="file" accept=".csv,text/csv" style={{ display: "none" }} onChange={e => { if (e.target.files[0]) onCSV(e.target.files[0]); }} />
          </div>
        }>
          <div className="people-table">
            <div className="people-row people-head">
              <div>Nome</div><div>Tag</div><div>Origem</div><div>Contato</div><div>Sessões</div><div></div>
            </div>
            {list.map(p => {
              const sessions = appointments.filter(a => a.personId === p.id);
              const tone = p.tag === "Cliente" ? "success" : p.tag === "Lead quente" ? "accent" : p.tag === "Avaliando" ? "warn" : "default";
              return (
                <div key={p.id} className="people-row clickable" onClick={() => openPerson(p)}>
                  <div>
                    <div className="strong">{p.name}</div>
                    {p.note && <div className="dim small ellipsis">{p.note}</div>}
                  </div>
                  <div><Pill tone={tone}>{p.tag}</Pill></div>
                  <div className="dim small">{p.source}</div>
                  <div>
                    <div className="small tabular">{p.phone}</div>
                    <div className="dim small">{p.email}</div>
                  </div>
                  <div className="tabular">{sessions.length}</div>
                  <div className="row-actions" onClick={e => e.stopPropagation()}>
                    <IconBtn title="Excluir" danger onClick={() => { if (confirm(`Excluir ${p.name}?`)) store.deletePerson(p.id); }}><Icon name="trash" /></IconBtn>
                  </div>
                </div>
              );
            })}
            {list.length === 0 && <EmptyState icon={<Icon name="people" size={28} />} title="Nenhum contato encontrado" />}
          </div>
        </Panel>

        <Panel title="Novo contato">
          <form onSubmit={submit} className="form">
            <div className="form-grid">
              <Field label="Nome" full><input value={form.name} onChange={e => set("name", e.target.value)} required /></Field>
              <Field label="WhatsApp" hint="Apenas dígitos. DDI 55 é adicionado.">
                <input value={form.phone} onChange={e => set("phone", e.target.value)} placeholder="11999999999" />
              </Field>
              <Field label="Email"><input type="email" value={form.email} onChange={e => set("email", e.target.value)} /></Field>
              <Field label="Tag">
                <select value={form.tag} onChange={e => set("tag", e.target.value)}>
                  <option>Lead quente</option><option>Lead frio</option><option>Avaliando</option><option>Cliente</option>
                </select>
              </Field>
              <Field label="Origem">
                <select value={form.source} onChange={e => set("source", e.target.value)}>
                  <option>Instagram</option><option>YouTube</option><option>LinkedIn</option><option>WhatsApp</option><option>Indicação</option><option>Outro</option>
                </select>
              </Field>
              <Field label="Anotação" full>
                <textarea rows="3" value={form.note} onChange={e => set("note", e.target.value)} placeholder="Contexto, dor, expectativa..." />
              </Field>
            </div>
            <div className="form-foot">
              <div style={{ flex: 1 }} />
              <Button type="submit">Salvar contato</Button>
            </div>
          </form>
          <div className="info-block">
            <div className="info-title">Formato CSV</div>
            <div className="dim small">Cabeçalhos: <code>name,phone,email,tag,source,note</code> (alguns sinônimos em PT também são aceitos: nome, telefone, origem, observação).</div>
          </div>
        </Panel>
      </div>
    </div>
  );
}

// --- Tarefas (Kanban with drag-and-drop) ------------------------------------
function Tasks({ store }) {
  const { tasks } = store.data;
  const [form, setForm] = useState({ title: "", category: "Comercial", priority: "alta", note: "" });
  const [dragId, setDragId] = useState(null);
  const [overLane, setOverLane] = useState(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = (e) => {
    e.preventDefault();
    if (!form.title) return;
    store.addTask(form);
    setForm({ title: "", category: "Comercial", priority: "alta", note: "" });
  };

  const lanes = [
    { key: "alta", label: "Alta prioridade", tone: "danger" },
    { key: "andamento", label: "Em andamento", tone: "warn" },
    { key: "depois", label: "Depois", tone: "default" },
  ];

  const handleDragStart = (e, id) => {
    setDragId(id);
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/plain", id);
  };
  const handleDragOver = (e, laneKey) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    setOverLane(laneKey);
  };
  const handleDrop = (e, laneKey) => {
    e.preventDefault();
    const id = dragId || e.dataTransfer.getData("text/plain");
    if (id) {
      const task = tasks.find(t => t.id === id);
      if (task && task.priority !== laneKey) {
        store.updateTask(id, { priority: laneKey });
      }
    }
    setDragId(null);
    setOverLane(null);
  };
  const handleDragEnd = () => { setDragId(null); setOverLane(null); };

  return (
    <div className="view-wrap">
      <Panel title="Nova tarefa">
        <form onSubmit={submit} className="form inline-form">
          <input className="grow" value={form.title} onChange={e => set("title", e.target.value)} placeholder="O que precisa ser feito?" required />
          <select value={form.category} onChange={e => set("category", e.target.value)}>
            <option>Comercial</option><option>Atendimento</option><option>Conteúdo</option><option>Administrativo</option><option>Pessoal</option>
          </select>
          <select value={form.priority} onChange={e => set("priority", e.target.value)}>
            <option value="alta">Alta</option><option value="andamento">Em andamento</option><option value="depois">Depois</option>
          </select>
          <input value={form.note} onChange={e => set("note", e.target.value)} placeholder="Observação (opcional)" />
          <Button type="submit">Adicionar</Button>
        </form>
      </Panel>

      <div className="kanban">
        {lanes.map(l => {
          const items = tasks.filter(t => t.priority === l.key);
          const isOver = overLane === l.key;
          return (
            <div
              key={l.key}
              className="kanban-col"
              data-over={isOver ? "1" : undefined}
              onDragOver={e => handleDragOver(e, l.key)}
              onDragLeave={() => setOverLane(null)}
              onDrop={e => handleDrop(e, l.key)}
            >
              <div className="kanban-head">
                <Pill tone={l.tone}>{l.label}</Pill>
                <span className="dim tabular">{items.length}</span>
              </div>
              <div className="kanban-list">
                {items.map(t => (
                  <div
                    key={t.id}
                    className="task-card"
                    draggable
                    data-dragging={dragId === t.id ? "1" : undefined}
                    onDragStart={e => handleDragStart(e, t.id)}
                    onDragEnd={handleDragEnd}
                  >
                    <div className="task-card-head">
                      <span className="task-grip" title="Arrastar"><Icon name="grip" size={14} /></span>
                      <div className="task-card-title">{t.title}</div>
                      <IconBtn title="Excluir" danger onClick={() => store.deleteTask(t.id)}><Icon name="x" size={14} /></IconBtn>
                    </div>
                    {t.note && <div className="task-card-note">{t.note}</div>}
                    <div className="task-card-foot">
                      <Pill>{t.category}</Pill>
                    </div>
                  </div>
                ))}
                {items.length === 0 && <div className="kanban-empty dim small">arraste tarefas para cá</div>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// --- Alertas -----------------------------------------------------------------
function Alerts({ store }) {
  const { alerts } = store.data;
  const [form, setForm] = useState({ title: "", level: "média", when: TODAY_ISO + " 09:00", note: "" });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = (e) => {
    e.preventDefault();
    if (!form.title) return;
    store.addAlert(form);
    setForm({ title: "", level: "média", when: TODAY_ISO + " 09:00", note: "" });
  };

  const groups = [
    { key: "alta", label: "Urgentes", tone: "danger" },
    { key: "média", label: "Atenção", tone: "warn" },
    { key: "baixa", label: "Acompanhar", tone: "default" },
  ];

  return (
    <div className="view-wrap">
      <Panel title="Novo alerta">
        <form onSubmit={submit} className="form inline-form">
          <input className="grow" value={form.title} onChange={e => set("title", e.target.value)} placeholder="Sobre o que é o alerta?" required />
          <select value={form.level} onChange={e => set("level", e.target.value)}>
            <option value="alta">Alta</option><option value="média">Média</option><option value="baixa">Baixa</option>
          </select>
          <input value={form.when} onChange={e => set("when", e.target.value)} placeholder="Quando (texto livre)" />
          <input value={form.note} onChange={e => set("note", e.target.value)} placeholder="Observação" />
          <Button type="submit">Adicionar</Button>
        </form>
      </Panel>

      {groups.map(g => {
        const items = alerts.filter(a => a.level === g.key);
        if (items.length === 0) return null;
        return (
          <Panel key={g.key} title={g.label} right={<Pill tone={g.tone}>{items.length}</Pill>}>
            <div className="list">
              {items.map(a => (
                <div key={a.id} className="alert-row big">
                  <div className="alert-text">
                    <div className="alert-title">{a.title}</div>
                    <div className="alert-meta dim">{a.when}{a.note ? ` — ${a.note}` : ""}</div>
                  </div>
                  <IconBtn title="Resolver" onClick={() => store.deleteAlert(a.id)}><Icon name="check" /></IconBtn>
                </div>
              ))}
            </div>
          </Panel>
        );
      })}

      {alerts.length === 0 && (
        <Panel title="Alertas"><EmptyState icon={<Icon name="bell" size={28} />} title="Nenhum alerta pendente" hint="Tudo sob controle." /></Panel>
      )}
    </div>
  );
}

// --- Notas / Conteúdos -------------------------------------------------------
function Notes({ store, filters }) {
  const { notes } = store.data;
  const [form, setForm] = useState({ title: "", tags: "", body: "" });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const submit = (e) => {
    e.preventDefault();
    if (!form.title) return;
    store.addNote({ title: form.title, tags: form.tags.split(",").map(s => s.trim()).filter(Boolean), body: form.body });
    setForm({ title: "", tags: "", body: "" });
  };

  const list = notes.filter(n => filters.q ? (n.title + n.body + (n.tags||[]).join(" ")).toLowerCase().includes(filters.q.toLowerCase()) : true);

  return (
    <div className="view-wrap">
      <Panel title="Nova ideia">
        <form onSubmit={submit} className="form">
          <div className="form-grid">
            <Field label="Título" full><input value={form.title} onChange={e => set("title", e.target.value)} placeholder="Frase, ideia, gancho..." required /></Field>
            <Field label="Tags" full hint="Separe por vírgula. Ex: carrossel, atrair">
              <input value={form.tags} onChange={e => set("tags", e.target.value)} />
            </Field>
            <Field label="Conteúdo" full>
              <textarea rows="3" value={form.body} onChange={e => set("body", e.target.value)} placeholder="Desenvolva a ideia..." />
            </Field>
          </div>
          <div className="form-foot">
            <div style={{ flex: 1 }} />
            <Button type="submit">Salvar nota</Button>
          </div>
        </form>
      </Panel>

      <Panel title="Notas e ideias" right={<Pill>{list.length}</Pill>}>
        <div className="notes-grid">
          {list.map(n => (
            <div key={n.id} className="note-card">
              <div className="note-head">
                <div className="note-title">{n.title}</div>
                <IconBtn title="Excluir" danger onClick={() => store.deleteNote(n.id)}><Icon name="trash" size={14} /></IconBtn>
              </div>
              {n.tags?.length > 0 && <div className="note-tags">{n.tags.map(t => <Pill key={t}>{t}</Pill>)}</div>}
              {n.body && <div className="note-body">{n.body}</div>}
            </div>
          ))}
          {list.length === 0 && <EmptyState icon={<Icon name="note" size={28} />} title="Nenhuma nota" />}
        </div>
      </Panel>
    </div>
  );
}

Object.assign(window, { Agendar, PeopleView, Tasks, Alerts, Notes });
