// View: Goals — each goal a winding trail with milestones.
// PRODUCTION-READY: CRUD completo (crear, editar, borrar, marcar milestones).

function ViewGoals() {
  const { lang } = window.useApp();
  const t = window.I18N[lang];
  const DATA = window.DATA;
  const Icon = window.Icon;

  const [filter, setFilter] = React.useState("in_progress");
  const [editing, setEditing] = React.useState(null);
  const [, force] = React.useReducer((x) => x + 1, 0);

  React.useEffect(() => {
    const unsub = window.Store.subscribe("goals", force);
    return unsub;
  }, []);

  const allGoals = DATA.goals;
  const filtered = allGoals.filter(g => g.status === filter);

  function handleIncrement(goal) {
    window.GoalOps.incrementMilestone(goal);
  }

  if (allGoals.length === 0) {
    return (
      <div className="content">
        <div className="card" style={{ padding: 60, textAlign: "center" }}>
          <div style={{ fontSize: 64, marginBottom: 16 }}>🏞️</div>
          <div className="serif" style={{ fontSize: 28, marginBottom: 8 }}>
            {lang === "es" ? "Aún sin metas" : "No goals yet"}
          </div>
          <div className="meta" style={{ fontSize: 15, marginBottom: 24, maxWidth: 380, margin: "0 auto 24px" }}>
            {lang === "es"
              ? "Las metas son senderos que decides caminar. Crea la primera y empieza a marcar hitos."
              : "Goals are trails you choose to walk. Create your first and start checking off milestones."}
          </div>
          <button className="btn warm" onClick={() => setEditing("new")} style={{ fontSize: 15 }}>
            <Icon name="plus" size={14}/> {t.new_goal}
          </button>
        </div>
        {editing && <GoalEditModal goal={editing === "new" ? null : editing} onClose={() => setEditing(null)} />}
      </div>
    );
  }

  return (
    <div className="content">
      <div className="card-flat" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "14px 18px", flexWrap: "wrap", gap: 8 }}>
        <div className="row">
          {["in_progress", "completed", "paused"].map(s => {
            const count = allGoals.filter(g => g.status === s).length;
            return (
              <button key={s}
                className={"btn " + (filter === s ? "primary" : "")}
                onClick={() => setFilter(s)}
                style={{ padding: "6px 14px" }}>
                {t[s]} <span className="meta" style={{ color: "inherit", opacity: 0.7, marginLeft: 4 }}>{count}</span>
              </button>
            );
          })}
        </div>
        <button className="btn warm" onClick={() => setEditing("new")}>
          <Icon name="plus" size={14}/> {t.new_goal}
        </button>
      </div>

      {filtered.length === 0 && (
        <div className="card" style={{ padding: 40, textAlign: "center" }}>
          <div className="serif italic" style={{ fontSize: 20, color: "var(--ink-3)" }}>
            {filter === "in_progress" && (lang === "es" ? "sin metas en curso" : "no goals in progress")}
            {filter === "completed" && (lang === "es" ? "sin metas completadas aún" : "no completed goals yet")}
            {filter === "paused" && (lang === "es" ? "sin metas pausadas" : "no paused goals")}
          </div>
        </div>
      )}

      {filtered.map(g => {
        const dueD = new Date(g.due);
        const today = DATA.TODAY;
        const startDate = new Date(g.startDate || g.createdAt || DATA.user.since);
        const milestones = Array.from({ length: g.milestones }, (_, i) => i);
        const goalColor = g.status === "completed" ? "var(--sage)" : g.status === "paused" ? "var(--ink-3)" : "var(--terracotta)";

        return (
          <div key={g.id} className="card" style={{ position: "relative" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 16, marginBottom: 14 }}>
              <div onClick={() => setEditing(g)} style={{ cursor: "pointer" }}>
                <div className="kicker">{getCategoryLabel(g.category, lang)}</div>
                <div className="serif" style={{ fontSize: 26, marginTop: 4 }}>{lang === "es" ? g.title_es : g.title_en}</div>
                <div className="meta" style={{ marginTop: 6, display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
                  <span>{t.by_date} {window.fmtDateShort(g.due, lang)} {dueD.getFullYear()} · {g.mdone || 0}/{g.milestones} {t.milestones}</span>
                  {g.status === "completed" && (
                    <button
                      className="pill sage"
                      style={{ cursor: "pointer", border: "none" }}
                      onClick={(e) => { e.stopPropagation(); window.celebrate && window.celebrate(); }}
                    >
                      ✦ {lang === "es" ? "Celebrar" : "Replay"}
                    </button>
                  )}
                </div>
              </div>
              <div style={{ textAlign: "right", display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end" }}>
                <div>
                  <div className="meta">{lang === "es" ? "Progreso" : "Progress"}</div>
                  <div style={{ fontFamily: "var(--font-display)", fontSize: 40, lineHeight: 1, letterSpacing: "-0.01em", color: goalColor }}>
                    {Math.round((g.progress || 0) * 100)}<span style={{ fontSize: 18, color: "var(--ink-3)" }}>%</span>
                  </div>
                </div>
                {g.status === "in_progress" && (g.mdone || 0) < g.milestones && (
                  <button className="btn warm" style={{ fontSize: 12, padding: "4px 10px" }}
                    onClick={(e) => { e.stopPropagation(); handleIncrement(g); }}>
                    + {lang === "es" ? "Hito" : "Milestone"}
                  </button>
                )}
              </div>
            </div>

            <div style={{ position: "relative", height: 80, padding: "0 12px" }}>
              <svg viewBox="0 0 1000 80" preserveAspectRatio="none" width="100%" height="80">
                <path d="M 0 60 C 200 10, 350 80, 500 40 S 800 10, 1000 50"
                  fill="none" stroke="var(--line)" strokeWidth="2" strokeDasharray="3 6"/>
                <defs>
                  <clipPath id={`clip-${g.id}`}>
                    <rect x="0" y="0" width={1000 * (g.progress || 0)} height="80"/>
                  </clipPath>
                </defs>
                <path d="M 0 60 C 200 10, 350 80, 500 40 S 800 10, 1000 50"
                  fill="none" stroke={goalColor}
                  strokeWidth="2.5" clipPath={`url(#clip-${g.id})`}/>

                {milestones.map(i => {
                  const frac = (i + 0.5) / g.milestones;
                  const done = i < (g.mdone || 0);
                  const isLast = i === (g.mdone || 0);
                  const x = frac * 1000;
                  const y = 60 + 40 * Math.sin(frac * Math.PI * 2.2) - 5;
                  return (
                    <g key={i} style={{ cursor: "pointer" }} onClick={(e) => { e.stopPropagation(); if (i === (g.mdone || 0)) handleIncrement(g); else if (i < (g.mdone || 0)) window.GoalOps.decrementMilestone(g); }}>
                      <circle cx={x} cy={y} r={done ? 5 : isLast ? 6 : 4}
                        fill={done ? goalColor : "var(--paper)"}
                        stroke={isLast && g.status === "in_progress" ? "var(--terracotta)" : (done ? "transparent" : "var(--line)")}
                        strokeWidth={isLast ? 2 : 1.5}/>
                      {isLast && g.status === "in_progress" && (
                        <circle cx={x} cy={y} r="10" fill="oklch(58% 0.13 35 / 0.15)"/>
                      )}
                    </g>
                  );
                })}
                <text x="4" y="76" fontSize="9" fontFamily="var(--font-mono)" fill="var(--ink-3)" letterSpacing="0.1em">
                  {window.fmtDateShort(startDate.toISOString().slice(0, 10), lang).toUpperCase()}
                </text>
                <text x="996" y="76" fontSize="9" fontFamily="var(--font-mono)" fill="var(--ink-3)" textAnchor="end" letterSpacing="0.1em">
                  {window.fmtDateShort(g.due, lang).toUpperCase()} {dueD.getFullYear()}
                </text>
              </svg>
            </div>

            {(g.subtasks || []).length > 0 && (
              <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line-soft)" }}>
                <div className="meta" style={{ marginBottom: 6 }}>{lang === "es" ? "Subtareas" : "Subtasks"}</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                  {g.subtasks.map((st, idx) => (
                    <div key={idx} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13 }}>
                      <button onClick={() => toggleSubtask(g, idx)} style={{
                        width: 16, height: 16, borderRadius: 4,
                        border: `1.5px solid ${st.done ? goalColor : "var(--line)"}`,
                        background: st.done ? goalColor : "transparent",
                        display: "grid", placeItems: "center", cursor: "pointer", padding: 0, flex: "0 0 16px",
                      }}>
                        {st.done && <Icon name="check" size={9} color="var(--paper)"/>}
                      </button>
                      <span style={{ textDecoration: st.done ? "line-through" : "none", opacity: st.done ? 0.6 : 1 }}>{st.title}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {(g.linkedHabits || []).length > 0 && (
              <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--line-soft)", display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                <span className="meta">{lang === "es" ? "Hábitos vinculados" : "Linked habits"}</span>
                <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
                  {g.linkedHabits.map(hid => {
                    const h = DATA.habits.find(x => x.id === hid);
                    if (!h) return null;
                    return (
                      <span key={hid} className="pill">
                        {h.emoji} {lang === "es" ? h.name_es : h.name_en} <span style={{ opacity: 0.6 }}>· {h.streak || 0}d</span>
                      </span>
                    );
                  })}
                </div>
              </div>
            )}
          </div>
        );
      })}

      {editing && <GoalEditModal goal={editing === "new" ? null : editing} onClose={() => setEditing(null)} />}
    </div>
  );
}

function getCategoryLabel(key, lang) {
  const c = (window.GOAL_CATEGORIES || []).find(c => c.key === key);
  if (!c) return lang === "es" ? "Otros" : "Other";
  return lang === "es" ? c.name_es : c.name_en;
}

function toggleSubtask(goal, idx) {
  const subtasks = [...(goal.subtasks || [])];
  subtasks[idx] = { ...subtasks[idx], done: !subtasks[idx].done };
  window.Storage.update("goals", goal.id, { subtasks });
}

function GoalEditModal({ goal, onClose }) {
  const { lang } = window.useApp();
  const Icon = window.Icon;
  const isEdit = !!goal;
  const habits = window.Storage.get("habits");

  const [title_es, setTitleEs] = React.useState(goal ? goal.title_es || "" : "");
  const [title_en, setTitleEn] = React.useState(goal ? goal.title_en || "" : "");
  const [category, setCategory] = React.useState(goal ? goal.category || "finance" : "finance");
  const [due, setDue] = React.useState(goal ? goal.due || nextYearISO() : nextYearISO());
  const [milestones, setMilestones] = React.useState(goal ? goal.milestones || 6 : 6);
  const [description, setDescription] = React.useState(goal ? goal.description || "" : "");
  const [subtasks, setSubtasks] = React.useState(goal ? goal.subtasks || [] : []);
  const [linkedHabits, setLinkedHabits] = React.useState(goal ? goal.linkedHabits || [] : []);
  const [status, setStatus] = React.useState(goal ? goal.status || "in_progress" : "in_progress");
  const [newSub, setNewSub] = React.useState("");
  const [error, setError] = React.useState(null);

  function addSubtask() {
    if (!newSub.trim()) return;
    setSubtasks([...subtasks, { title: newSub.trim(), done: false }]);
    setNewSub("");
  }
  function removeSubtask(i) {
    setSubtasks(subtasks.filter((_, idx) => idx !== i));
  }
  function toggleHabit(hid) {
    setLinkedHabits(linkedHabits.includes(hid) ? linkedHabits.filter(x => x !== hid) : [...linkedHabits, hid]);
  }

  function handleSubmit(e) {
    e.preventDefault();
    setError(null);
    if (!title_es.trim()) { setError(lang === "es" ? "Pon un título" : "Add a title"); return; }
    if (!due) { setError(lang === "es" ? "Fecha objetivo requerida" : "Target date required"); return; }
    const m = Math.max(1, Math.min(50, parseInt(milestones, 10) || 1));
    const mdone = (goal && goal.mdone) || 0;
    const payload = {
      title_es: title_es.trim(),
      title_en: title_en.trim() || title_es.trim(),
      category,
      due,
      milestones: m,
      mdone: Math.min(mdone, m),
      progress: Math.min(mdone, m) / m,
      status,
      description,
      subtasks,
      linkedHabits,
      startDate: (goal && goal.startDate) || window.todayISO(),
    };
    if (isEdit) {
      window.Storage.update("goals", goal.id, payload);
    } else {
      window.Storage.add("goals", payload);
    }
    onClose();
  }

  function handleDelete() {
    if (!isEdit) return;
    const msg = lang === "es" ? `Borrar "${goal.title_es}"?` : `Delete "${goal.title_en}"?`;
    if (window.confirm(msg)) {
      window.Storage.remove("goals", goal.id);
      onClose();
    }
  }

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal-card" style={{ maxWidth: 540, padding: 24, maxHeight: "85vh", overflowY: "auto" }} onClick={(e) => e.stopPropagation()}>
        <button className="ob-close" onClick={onClose} aria-label="close">
          <Icon name="x" size={14} />
        </button>
        <div className="kicker">{isEdit ? (lang === "es" ? "Editar meta" : "Edit goal") : (lang === "es" ? "Nueva meta" : "New goal")}</div>
        <div className="h2" style={{ marginBottom: 20, marginTop: 4 }}>{title_es || (lang === "es" ? "Meta" : "Goal")}</div>

        <form onSubmit={handleSubmit}>
          <div className="form-row">
            <label className="form-label">{lang === "es" ? "Título (es)" : "Title (es)"}</label>
            <input type="text" className="input" value={title_es} onChange={(e) => setTitleEs(e.target.value)} placeholder={lang === "es" ? "Ahorrar S/ 6,000" : "Save S/ 6,000"} required autoFocus/>
          </div>
          <div className="form-row">
            <label className="form-label">{lang === "es" ? "Título (en)" : "Title (en)"}</label>
            <input type="text" className="input" value={title_en} onChange={(e) => setTitleEn(e.target.value)} placeholder="Save $1,500 (optional)"/>
          </div>

          <div className="form-row" style={{ display: "flex", gap: 12 }}>
            <div style={{ flex: 1 }}>
              <label className="form-label">{lang === "es" ? "Categoría" : "Category"}</label>
              <select className="input" value={category} onChange={(e) => setCategory(e.target.value)}>
                {(window.GOAL_CATEGORIES || []).map(c => (
                  <option key={c.key} value={c.key}>{lang === "es" ? c.name_es : c.name_en}</option>
                ))}
              </select>
            </div>
            <div style={{ flex: 1 }}>
              <label className="form-label">{lang === "es" ? "Estado" : "Status"}</label>
              <select className="input" value={status} onChange={(e) => setStatus(e.target.value)}>
                <option value="in_progress">{lang === "es" ? "En curso" : "In progress"}</option>
                <option value="paused">{lang === "es" ? "Pausada" : "Paused"}</option>
                <option value="completed">{lang === "es" ? "Completada" : "Completed"}</option>
              </select>
            </div>
          </div>

          <div className="form-row" style={{ display: "flex", gap: 12 }}>
            <div style={{ flex: 1 }}>
              <label className="form-label">{lang === "es" ? "Fecha objetivo" : "Target date"}</label>
              <input type="date" className="input" value={due} onChange={(e) => setDue(e.target.value)} required/>
            </div>
            <div style={{ flex: 1 }}>
              <label className="form-label">{lang === "es" ? "Nº de hitos" : "Milestones"}</label>
              <input type="number" className="input mono" min="1" max="50" value={milestones} onChange={(e) => setMilestones(e.target.value)}/>
            </div>
          </div>

          <div className="form-row">
            <label className="form-label">{lang === "es" ? "Descripción" : "Description"}</label>
            <textarea className="input" rows={2} value={description} onChange={(e) => setDescription(e.target.value)}/>
          </div>

          <div className="form-row">
            <label className="form-label">{lang === "es" ? "Subtareas" : "Subtasks"}</label>
            <div style={{ display: "flex", gap: 6, marginBottom: 6 }}>
              <input type="text" className="input" value={newSub} onChange={(e) => setNewSub(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addSubtask(); } }}
                placeholder={lang === "es" ? "Agregar subtarea..." : "Add subtask..."} style={{ flex: 1 }}/>
              <button type="button" className="btn" onClick={addSubtask}>+</button>
            </div>
            {subtasks.map((st, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 0" }}>
                <span style={{ flex: 1, fontSize: 13 }}>{st.title}</span>
                <button type="button" onClick={() => removeSubtask(i)} className="btn" style={{ fontSize: 11, padding: "2px 8px" }}>−</button>
              </div>
            ))}
          </div>

          {habits.length > 0 && (
            <div className="form-row">
              <label className="form-label">{lang === "es" ? "Hábitos vinculados" : "Linked habits"}</label>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                {habits.map(h => (
                  <button type="button" key={h.id} onClick={() => toggleHabit(h.id)}
                    className={"pill" + (linkedHabits.includes(h.id) ? " warm" : "")}
                    style={{ cursor: "pointer", border: linkedHabits.includes(h.id) ? "1px solid var(--terracotta)" : "1px solid var(--line)" }}>
                    {h.emoji} {lang === "es" ? h.name_es : h.name_en}
                  </button>
                ))}
              </div>
            </div>
          )}

          {error && <div className="form-error">{error}</div>}

          <div className="form-actions">
            {isEdit && (
              <button type="button" className="btn danger" onClick={handleDelete}>
                {lang === "es" ? "Borrar" : "Delete"}
              </button>
            )}
            <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
              <button type="button" className="btn" onClick={onClose}>{lang === "es" ? "Cancelar" : "Cancel"}</button>
              <button type="submit" className="btn warm">{isEdit ? (lang === "es" ? "Guardar" : "Save") : (lang === "es" ? "Crear" : "Create")}</button>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

function nextYearISO() {
  const d = new Date();
  d.setFullYear(d.getFullYear() + 1);
  return d.toISOString().slice(0, 10);
}

window.ViewGoals = ViewGoals;
window.GoalEditModal = GoalEditModal;
