// shareview.jsx — offentlig, read-only visning af en delt bordplan.
// Henter projektet via getSharedPlan (Cloud Function, ingen login) og viser
// oversigten. Ingen redigering er mulig.
const { useState: useStateSV, useEffect: useEffectSV } = React;

function SharedView({ shareId }) {
  const [state, setState] = useStateSV('loading'); // loading | ok | error
  const [project, setProject] = useStateSV(null);
  const [error, setError] = useStateSV('');
  const [fbReady, setFbReady] = useStateSV(!!window.PlaniqFirebase);

  useEffectSV(() => {
    if (window.PlaniqFirebase) { setFbReady(true); return; }
    const onReady = () => setFbReady(true);
    window.addEventListener('planiq-firebase-ready', onReady);
    return () => window.removeEventListener('planiq-firebase-ready', onReady);
  }, []);

  useEffectSV(() => {
    if (!fbReady) return;
    let alive = true;
    window.PlaniqFirebase.getSharedPlan(shareId)
      .then((p) => { if (alive) { setProject(p); setState('ok'); } })
      .catch((e) => { if (alive) { setError(e.message || 'Linket kunne ikke åbnes.'); setState('error'); } });
    return () => { alive = false; };
  }, [fbReady, shareId]);

  if (state === 'loading') {
    return (
      <div className="center" style={{ height: '100%', flexDirection: 'column', gap: 16, background: 'var(--bg)' }}>
        <LogoMark size={48} />
        <span className="pw-spinner" />
      </div>
    );
  }

  if (state === 'error') {
    return (
      <div className="center" style={{ height: '100%', background: 'var(--bg)' }}>
        <div className="card" style={{ padding: 36, textAlign: 'center', maxWidth: 420 }}>
          <div className="center" style={{ marginBottom: 16 }}><LogoMark size={48} /></div>
          <h2 style={{ marginBottom: 8 }}>Linket virker ikke</h2>
          <p className="muted" style={{ fontSize: 16, lineHeight: 1.5 }}>{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="scroll" style={{ height: '100%', background: 'var(--bg)' }}>
      {/* read-only topbjælke */}
      <div className="row" style={{ padding: '14px 24px', borderBottom: '1px solid var(--line)', background: 'var(--surface)', justifyContent: 'space-between', position: 'sticky', top: 0, zIndex: 5 }}>
        <Logo size={28} />
        <span className="chip" style={{ background: 'var(--surface-2)' }}><Icon name="link" size={15} /> Delt visning · kun læsning</span>
      </div>
      <SharedPlan project={project} />
      <div className="center" style={{ padding: '8px 0 40px' }}>
        <a className="btn btn-sm btn-ghost" href="https://bordplan.ooniq.app">Lavet med Planiq Bordplan</a>
      </div>
    </div>
  );
}

// Selve plan-oversigten (genbruger samme udseende som Oversigt-fanen, uden knapper).
function SharedPlan({ project }) {
  const TYPES = window.PlaniqData.PROJECT_TYPES;
  const DIET = window.PlaniqData.DIET_TYPES;
  const type = TYPES.find(t => t.id === project.type) || TYPES[4];
  const tableGuests = (tid) => project.guests.filter(g => g.seat && g.seat.tableId === tid).sort((a, b) => a.seat.index - b.seat.index);
  const unplaced = project.guests.filter(g => !g.seat);
  const groupColor = (id) => (project.groups.find(g => g.id === id) || {}).color || 1;
  const dietTally = (tid) => { const t = {}; tableGuests(tid).forEach(g => g.diet.forEach(d => t[d] = (t[d] || 0) + 1)); return t; };
  const totalHeads = project.guests.reduce((s, g) => s + 1 + (g.plusOne ? 1 : 0), 0);

  return (
    <div style={{ maxWidth: 900, margin: '0 auto', padding: '32px 28px 40px' }}>
      {/* header */}
      <div className="row" style={{ justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 26, paddingBottom: 20, borderBottom: '2px solid var(--line)', flexWrap: 'wrap', gap: 16 }}>
        <div className="row gap-3" style={{ alignItems: 'center' }}>
          {project.coverImage
            ? <img src={project.coverImage} alt="" style={{ width: 56, height: 56, borderRadius: 14, objectFit: 'cover' }} />
            : <span style={{ width: 56, height: 56, borderRadius: 14, display: 'grid', placeItems: 'center', background: `var(--grp-${project.cover || 1})` }}><Icon name={type.icon} size={28} color="#fff" /></span>}
          <div>
            <h1 style={{ fontSize: 32, marginBottom: 4 }}>{project.name}</h1>
            <p className="muted" style={{ fontSize: 16, fontWeight: 700 }}>{fmtDate(project.date)}{project.venue ? ' · ' + project.venue : ''}</p>
          </div>
        </div>
        <p className="faint" style={{ fontSize: 13.5, fontWeight: 800 }}>{project.guests.length} gæster · {totalHeads} kuverter · {project.tables.length} borde</p>
      </div>

      {/* tables */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 18 }}>
        {project.tables.map(t => {
          const gs = tableGuests(t.id);
          const dt = dietTally(t.id); const dk = Object.keys(dt);
          return (
            <div key={t.id} className="card" style={{ padding: '16px 18px' }}>
              <div className="row" style={{ justifyContent: 'space-between', marginBottom: 10, alignItems: 'flex-start' }}>
                <h3 style={{ fontSize: 18, lineHeight: 1.15 }}>{t.label}</h3>
                <span className="chip" style={{ background: 'var(--surface-2)' }}>{gs.length}/{t.seats}</span>
              </div>
              {gs.length === 0 ? <p className="faint" style={{ fontSize: 14.5, fontWeight: 700, padding: '8px 0' }}>Ingen placeret endnu</p> : (
                <ol style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 7 }}>
                  {gs.map((g, i) => (
                    <li key={g.id} className="row gap-2" style={{ fontSize: 15 }}>
                      <span style={{ width: 22, fontWeight: 800, color: 'var(--ink-faint)', fontSize: 13 }}>{i + 1}.</span>
                      <span style={{ width: 8, height: 8, borderRadius: '50%', background: `var(--grp-${groupColor(g.group)})`, flex: 'none' }}></span>
                      <span style={{ fontWeight: 700 }}>{g.name}</span>
                      {g.child && <Icon name="baby" size={13} color="var(--ink-faint)" />}
                      {g.plusOne && <span className="faint" style={{ fontSize: 13, fontWeight: 800 }}>+1</span>}
                      {g.diet.length > 0 && <span className="faint" style={{ fontSize: 12, fontWeight: 800 }}>{g.diet.map(d => DIET.find(x => x.id === d)?.short).join(', ')}</span>}
                    </li>
                  ))}
                </ol>
              )}
              {dk.length > 0 && (
                <div className="row gap-2" style={{ marginTop: 12, paddingTop: 10, borderTop: '1px dashed var(--line)', flexWrap: 'wrap' }}>
                  {dk.map(d => <span key={d} className="chip" style={{ height: 24, background: 'var(--sage-tint)', color: 'var(--sage-deep)', border: 'none', fontSize: 11.5 }}><Icon name="leaf" size={11} />{DIET.find(x => x.id === d)?.short} {dt[d]}</span>)}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {unplaced.length > 0 && (
        <div className="card" style={{ padding: '16px 18px', marginTop: 18 }}>
          <h3 style={{ fontSize: 17, marginBottom: 10 }}>Ikke placeret ({unplaced.length})</h3>
          <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
            {unplaced.map(g => (
              <span key={g.id} className="chip" style={{ background: 'var(--surface-2)' }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: `var(--grp-${groupColor(g.group)})` }}></span>{g.name}
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { SharedView, SharedPlan });
