// Phase 6c. Shared-file wiring and the scoped CSS live in docs/phase6c-wiring.md.
(function () {
  const T = window.AreteTaxes;
  const { Loading, LoadError, NoData, Icon } = window;

  function TaxDeadlines() {
    const t = window.useTables(["tax_deadlines"]);
    const today = window.todayNY();
    if (t.status === "loading") return <Loading />;
    if (t.status === "error") return <LoadError error={t.error} onRetry={t.reload} />;
    const groups = T.deadlineGroups(t.data.tax_deadlines || [], today);
    if (!groups.length) return <NoData>No tax deadlines yet.</NoData>;
    return <>{groups.map(group => <section key={group.name} aria-label={group.name + " tax deadlines"}>
      <div className="secthead"><h2>{group.name}</h2></div>
      {group.rows.map(row => {
        const state = T.deadlineState(row, today);
        return <article className="dl-card" key={row.id}>
          <time className="when" dateTime={row.due_date} aria-label={T.dateLabel(row.due_date)}>
            <span>{T.dateLabel(row.due_date, { day: undefined, year: undefined })}</span>
            <b>{Number(row.due_date.slice(8, 10))}</b><span>{row.due_date.slice(0, 4)}</span>
          </time>
          <div className="tax-deadline-body"><div className="tax-name">{row.name}</div>
            {row.notes && <div className="tax-muted tax-text">{row.notes}</div>}
            {row.needs_confirmation && <div className="tax-muted">Confirm with CPA</div>}
            {row.source_ref && <div className="tax-source">Source: {row.source_ref}</div>}
          </div>
          <span className={"chip tax-due " + (state.tone === "urgent" ? "tax-urgent" : "")}>{state.label}</span>
        </article>;
      })}
    </section>)}</>;
  }

  function TaxHoursBlock({ showEntries = false }) {
    const t = window.useTables(["tax_time_entries"]);
    const today = window.todayNY();
    const [year, setYear] = React.useState(+today.slice(0, 4));
    const [target, setTarget] = React.useState(500);
    if (t.status === "loading") return <Loading height={220} />;
    if (t.status === "error") return <LoadError error={t.error} onRetry={t.reload} />;
    const rows = t.data.tax_time_entries || [];
    if (!rows.length) return <NoData>No time log entries yet.</NoData>;
    const available = T.years(rows, today);
    const selected = available.includes(year) ? year : +today.slice(0, 4);
    const s = T.hoursSummary(rows, { year: selected, today, target });
    const h = T.formatHours;
    return <section>
      <div className="secthead"><h2>Material participation hours</h2>
        <label className="tax-control">Year <select value={selected} onChange={e => setYear(+e.target.value)}>
          {available.map(y => <option key={y} value={y}>{y}</option>)}</select></label>
        <label className="tax-control">View <select value={target} onChange={e => setTarget(+e.target.value)}>
          <option value={500}>500-hour test</option><option value={100}>100-hour test</option></select></label>
      </div>
      {!s.count ? <NoData>No logged hours for {selected} through {T.dateLabel(today)}.</NoData> : <>
        <div className="tax-kpi">
          <div className="tax-hour-head"><b className="num">{h(s.total)} of {target} hours</b>
            <span className="tax-muted">Ryan {h(s.people.ryan)} · Addie {h(s.people.addie)}</span></div>
          <div className="progress" role="progressbar" aria-label={`${selected} logged hours toward ${target} hours`}
            aria-valuemin={0} aria-valuemax={target} aria-valuenow={Math.min(s.total, target)}
            aria-valuetext={`${h(s.total)} logged hours; ${target}-hour reference`}>
            <i style={{ width: s.percent + "%" }} /></div>
          <div className="tax-muted">Logged in the time log · {s.count} {s.count === 1 ? "entry" : "entries"}</div>
          <div className="tax-muted tax-hours-note">Before in service: {h(s.preService)} · In service: {h(s.inService)} · Reconstructed: {h(s.reconstructed)}</div>
        </div>
        <p className="sub tax-hours-note">Logged hours include setup work. The CPA still needs to confirm which hours count.
          {target === 100 ? " The 100-hour test also needs more than 100 qualifying hours and at least as many as any other individual. Other workers’ hours are not in this log."
            : " The 500-hour test needs more than 500 qualifying hours."}</p>
        {showEntries && <div className="tcard scrollx" role="region" aria-label="Time log" tabIndex={0}>
          <table className="tbl tax-hours-table"><caption className="sr">{selected} time log through {T.dateLabel(today)}</caption>
            <thead><tr><th>Date</th><th>Person</th><th className="r">Hours</th><th>Activity</th><th>Notes</th></tr></thead>
            <tbody>{s.rows.map(row => <tr key={row.id}>
              <td className="num">{T.dateLabel(row.date)}</td><td>{row.person === "ryan" ? "Ryan" : "Addie"}</td>
              <td className="r num">{h(row.hours)}</td><td>{row.activity}
                <span className="th2">{row.date < row.service_date ? "Before in service" : "In service"}{row.reconstructed ? " · Reconstructed" : ""}</span></td>
              <td className="tax-text">{row.notes || "—"}</td>
            </tr>)}</tbody>
          </table>
        </div>}
      </>}
      {s.futureEntries > 0 && <p className="sub">{s.futureEntries} future-dated {s.futureEntries === 1 ? "entry is" : "entries are"} left out of the totals.</p>}
    </section>;
  }

  function TaxDeadlinesPage() {
    return <div className="phase6c"><TaxDeadlines /><TaxHoursBlock /></div>;
  }
  function TaxHoursPage() {
    return <div className="phase6c"><TaxHoursBlock showEntries /></div>;
  }
  function TaxCPAPage() {
    const t = window.useTables(["tax_cpa_questions"]);
    if (t.status === "loading") return <Loading />;
    if (t.status === "error") return <LoadError error={t.error} onRetry={t.reload} />;
    const groups = T.questionGroups(t.data.tax_cpa_questions || []);
    if (!groups.length) return <NoData>No CPA questions yet.</NoData>;
    return <div className="phase6c">{groups.map(group => <section key={group.name}>
      <div className="secthead"><h2>{group.name}</h2></div>
      <div className="tcard tax-questions">{group.questions.map(q => <article className="tax-question" key={q.id}>
        <div className="tax-question-head"><b>{q.question_number ? `Question ${q.question_number}` : "Open question"}</b>{q.urgent && <span className="chip tax-urgent">Time-sensitive</span>}</div>
        <p className="tax-text">{q.question}</p>
      </article>)}</div>
    </section>)}</div>;
  }
  function TaxDocsPage() {
    const t = window.useTables(["tax_documents"]);
    if (t.status === "loading") return <Loading />;
    if (t.status === "error") return <LoadError error={t.error} onRetry={t.reload} />;
    const summary = T.documentSummary(t.data.tax_documents || []);
    if (!summary.rows.length) return <NoData>No document checklist yet.</NoData>;
    const checklist = summary.rows.filter(row => !row.filename);
    const files = summary.rows.filter(row => row.filename);
    return <div className="phase6c">{[["Document checklist", checklist], ["Files on hand", files]].map(([title, rows]) => <section key={title}>
      <div className="secthead"><h2>{title}</h2>{title === "Document checklist" && <span className="tax-muted">
        {rows.filter(r => r.status === "have").length} have · {rows.filter(r => r.status === "missing").length} missing</span>}</div>
      {!rows.length ? <NoData>No {title.toLowerCase()} yet.</NoData> : <div className="tcard tax-docs">{rows.map(row => <article className="tax-doc" key={row.id}>
        <span className="tax-doc-mark" aria-hidden="true"><Icon name={row.status === "have" ? "check" : "file"} size={20} /></span>
        <div className="tax-doc-body"><div className="tax-name">{row.name}</div>
          {row.notes && <div className="tax-muted tax-text">{row.notes}</div>}
          {row.filename && <div className="tax-source">{row.filename}</div>}</div>
        <span className={"chip " + (row.status === "missing" ? "tax-urgent" : "")}>{row.status === "have" ? "Have" : "Missing"}</span>
      </article>)}</div>}
    </section>)}</div>;
  }
  window.ARETE_PAGES = Object.assign(window.ARETE_PAGES || {}, {
    "taxes/deadlines": TaxDeadlinesPage, "taxes/cpa": TaxCPAPage,
    "taxes/hours": TaxHoursPage, "taxes/docs": TaxDocsPage,
  });
})();
