// Plan & timeline — the approved project plan rendered as a gantt (features across
// ISO weeks, holiday weeks greyed, bars colored by phase — design spec §3.6). Page
// tier: owns the plan fetch; composes window.Timeline (unchanged) via
// window.PlanToGantt. No polling — a launched plan is sealed (hash-locked at
// approval), so a single fetch per project is enough.
const { useState, useEffect, useMemo } = React;

const PlanPage = ({ slug }) => {
  const [plan, setPlan] = useState(null);
  const [loadError, setLoadError] = useState(null);

  useEffect(() => {
    if (!slug) return undefined;
    let cancelled = false;
    window.Api.getProjectPlan(slug)
      .then((p) => { if (!cancelled) { setPlan(p); setLoadError(null); } })
      .catch((err) => { if (!cancelled) setLoadError(err); });
    return () => { cancelled = true; };
  }, [slug]);

  const gantt = useMemo(
    () => (plan && window.PlanToGantt ? window.PlanToGantt.planToGantt(plan) : null),
    [plan]
  );
  // An empty plan {} (project not launched, or no plan.json yet) has no features —
  // show the empty state instead of an empty grid.
  const hasPlan = !!(plan && Array.isArray(plan.features) && plan.features.length);

  if (loadError) {
    return <div className="max-w-5xl mx-auto p-10 text-center text-red-600">Could not load the plan: {loadError.message}</div>;
  }
  if (!plan) {
    return <div className="max-w-5xl mx-auto p-10 text-center text-neutral-400">Loading plan…</div>;
  }

  return (
    <div className="max-w-5xl mx-auto px-6 py-8">
      <div className="flex items-baseline justify-between mb-6">
        <h1 className="text-xl font-bold text-neutral-900">Plan &amp; timeline</h1>
        {hasPlan && gantt && (
          <span className="text-sm text-neutral-500">
            {gantt.rows.length} scheduled · {gantt.unscheduled.length} unscheduled
          </span>
        )}
      </div>
      {hasPlan ? (
        <div className="rounded-2xl border border-neutral-200 bg-white px-5 py-4">
          <window.Timeline gantt={gantt} />
        </div>
      ) : (
        <div className="rounded-2xl border border-dashed border-neutral-300 bg-white px-6 py-14 text-center text-neutral-400">
          No plan for this project yet. The plan &amp; timeline appears once the project is launched from the create flow.
        </div>
      )}
    </div>
  );
};

window.PlanPage = PlanPage;
