// Detail view — Info tab content (shown when user clicks an opdracht card)

// Section card wrapper
const Section = ({ title, action, children, noPadding = false }) => {
  const P = window.PICO;
  return (
    <div style={{
      background: '#fff', borderRadius: 12, marginBottom: 14,
      boxShadow: '0 1px 2px rgba(14,31,59,0.04)',
      border: '1px solid rgba(14,31,59,0.04)',
      overflow: 'hidden',
    }}>
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '16px 18px 14px',
      }}>
        <h3 style={{
          fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 800,
          fontSize: 17, color: P.ink, letterSpacing: -0.4, margin: 0,
        }}>{title}</h3>
        {action}
      </div>
      <div style={{ height: 1, background: P.borderSoft, margin: '0 18px' }} />
      <div style={{ padding: noPadding ? 0 : '14px 18px 18px' }}>
        {children}
      </div>
    </div>
  );
};

// Key-value row inside a section (side-by-side or stacked)
const KV = ({ label, value, editable = false, underline = false }) => {
  const P = window.PICO;
  return (
    <div>
      <div style={{
        fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 400,
        fontSize: 14, color: P.muted, letterSpacing: -0.1, marginBottom: 4,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <span>{label}</span>
        {editable && <IcPencil size={16} color={P.muted} />}
      </div>
      {value && (
        <div style={{
          fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 500,
          fontSize: 15, color: P.ink, letterSpacing: -0.2,
          textDecoration: underline ? 'underline' : 'none',
          textDecorationColor: 'rgba(14,31,59,0.3)',
          textUnderlineOffset: 3,
        }}>{value}</div>
      )}
    </div>
  );
};

// Status dropdown button in the "Opdracht status" row
const StatusDropdown = ({ status, onChange }) => {
  const P = window.PICO;
  const [open, setOpen] = React.useState(false);
  const allStatuses = [
    { key: 'matchen', label: 'Matchen' },
    { key: 'accepteren', label: 'Accepteren' },
    { key: 'offerte', label: 'Offerte' },
    { key: 'schouwen', label: 'Schouwen' },
    { key: 'installeren', label: 'Installeren' },
  ];

  const map = {
    offerte: { bg: P.offerteBg, fg: P.offerteFg },
    installeren: { bg: P.installerenBg, fg: P.installerenFg },
    schouwen: { bg: P.schouwenBg, fg: P.schouwenFg },
    accepteren: { bg: P.accepterenBg, fg: P.accepterenFg },
    matchen: { bg: P.matchenBg, fg: P.matchenFg },
  };
  const s = map[status.key];

  return (
    <div style={{ position: 'relative' }}>
      <button
        onClick={() => setOpen(v => !v)}
        style={{
          display: 'flex', alignItems: 'stretch', border: 'none', padding: 0,
          borderRadius: 6, overflow: 'hidden', cursor: 'pointer',
          background: s.bg, color: s.fg,
          fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 600,
          fontSize: 15, letterSpacing: -0.2,
        }}>
        <span style={{ padding: '8px 14px' }}>{status.label}</span>
        <span style={{
          display: 'flex', alignItems: 'center', padding: '0 10px',
          borderLeft: `1px solid ${s.fg}20`,
        }}>
          <IcChevD size={16} color={s.fg} />
        </span>
      </button>
      {open && (
        <>
          <div
            onClick={() => setOpen(false)}
            style={{ position: 'fixed', inset: 0, zIndex: 10 }}
          />
          <div style={{
            position: 'absolute', top: '100%', right: 0, marginTop: 6,
            background: '#fff', borderRadius: 10, zIndex: 11,
            boxShadow: '0 6px 24px rgba(14,31,59,0.12), 0 1px 3px rgba(14,31,59,0.08)',
            padding: 6, minWidth: 160,
            border: '1px solid rgba(14,31,59,0.06)',
          }}>
            {allStatuses.map(st => (
              <div
                key={st.key}
                onClick={() => { onChange(st); setOpen(false); }}
                style={{
                  padding: '8px 10px', borderRadius: 6, cursor: 'pointer',
                  fontFamily: '"Plus Jakarta Sans", system-ui', fontSize: 14,
                  color: P.ink, letterSpacing: -0.1,
                  background: st.key === status.key ? P.bg : 'transparent',
                }}
                onMouseEnter={e => e.currentTarget.style.background = P.bg}
                onMouseLeave={e => e.currentTarget.style.background = st.key === status.key ? P.bg : 'transparent'}
              >{st.label}</div>
            ))}
          </div>
        </>
      )}
    </div>
  );
};

// Overzicht content (the default sub-tab)
const OverzichtTab = ({ item, onStatusChange }) => {
  const P = window.PICO;
  return (
    <>
      {/* Oplevering card */}
      <div style={{
        background: '#fff', borderRadius: 12, padding: '16px 18px',
        marginBottom: 14, boxShadow: '0 1px 2px rgba(14,31,59,0.04)',
        border: '1px solid rgba(14,31,59,0.04)',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <h3 style={{
          fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 800,
          fontSize: 18, color: P.ink, letterSpacing: -0.4, margin: 0,
        }}>Oplevering</h3>
        <button style={{
          display: 'flex', alignItems: 'center', gap: 8,
          background: P.red, color: '#fff', border: 'none',
          padding: '10px 16px', borderRadius: 8, cursor: 'pointer',
          fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 700,
          fontSize: 15, letterSpacing: -0.2,
          boxShadow: '0 1px 2px rgba(241,75,56,0.2)',
        }}>
          Opleveren <IcCheck size={16} color="#fff" />
        </button>
      </div>

      {/* Klantinfo */}
      <Section title="Klantinfo">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <KV label="Bewoner" value={item.customer} />
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <KV label="E-mail" value={item.email || '—'} underline={!!item.email} />
            <KV label="Telefoon" value={item.phone || '—'} underline={!!item.phone} />
          </div>
          <HouseHeroSvg variant={item.thumb.tone} />
        </div>
        <div style={{
          textAlign: 'center', paddingTop: 18, marginTop: 14,
          borderTop: `1px solid ${P.borderSoft}`, marginLeft: -18, marginRight: -18,
          marginBottom: -18, padding: '18px 0',
        }}>
          <button style={{
            background: 'none', border: 'none', cursor: 'pointer',
            color: P.red, fontFamily: '"Plus Jakarta Sans", system-ui',
            fontWeight: 700, fontSize: 16, letterSpacing: -0.2,
          }}>Meer info</button>
        </div>
      </Section>

      {/* Opdrachtomschrijving */}
      <Section title="Opdrachtomschrijving">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <KV label="Ontstaan uit" value={item.origin} />
          <KV label="Eigenaar" value={item.owner} editable />
        </div>
      </Section>

      {/* Gekoppelde installateur */}
      <Section title="Gekoppelde installateur" action={<IcPencil size={18} color={P.muted} />}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        }}>
          <span style={{
            fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 400,
            fontSize: 14, color: P.muted, letterSpacing: -0.1,
          }}>Installateur keuze</span>
          <span style={{
            fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 700,
            fontSize: 15, color: P.ink, letterSpacing: -0.2,
          }}>{item.installer || '—'}</span>
        </div>
      </Section>

      {/* Afspraken */}
      <Section title="Afspraken">
        {item.afspraken.length > 0 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 12 }}>
            {item.afspraken.map(a => (
              <div key={a.id} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '12px 14px', background: P.bg, borderRadius: 10,
              }}>
                <div>
                  <div style={{
                    fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 700,
                    fontSize: 14.5, color: P.ink, letterSpacing: -0.2,
                  }}>{a.title}</div>
                  <div style={{
                    fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 400,
                    fontSize: 13, color: P.mutedStrong, letterSpacing: -0.1, marginTop: 2,
                  }}>{a.date} · {a.time}</div>
                </div>
                <IcChevR size={16} color={P.muted} />
              </div>
            ))}
          </div>
        )}
        <button style={{
          width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
          gap: 8, padding: '14px', background: 'none',
          border: `1px solid ${P.red}`, borderRadius: 10, cursor: 'pointer',
          color: P.red, fontFamily: '"Plus Jakarta Sans", system-ui',
          fontWeight: 700, fontSize: 15, letterSpacing: -0.2,
        }}>
          Nieuwe afspraak <IcPlus size={16} color={P.red} />
        </button>
      </Section>

      {/* Offertes */}
      <Section title="Offertes">
        {item.offertes > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 12 }}>
            {Array.from({ length: item.offertes }).map((_, i) => (
              <div key={i} style={{
                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                padding: '12px 14px', background: P.bg, borderRadius: 10,
              }}>
                <div>
                  <div style={{
                    fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 700,
                    fontSize: 14.5, color: P.ink, letterSpacing: -0.2,
                  }}>Offerte #{i + 1}</div>
                  <div style={{
                    fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 400,
                    fontSize: 13, color: P.mutedStrong, letterSpacing: -0.1, marginTop: 2,
                  }}>€ {(3200 + i * 900).toLocaleString('nl-NL')},00 · In behandeling</div>
                </div>
                <IcChevR size={16} color={P.muted} />
              </div>
            ))}
          </div>
        ) : null}
        <button style={{
          width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
          gap: 8, padding: '14px', background: 'none',
          border: `1px solid ${P.red}`, borderRadius: 10, cursor: 'pointer',
          color: P.red, fontFamily: '"Plus Jakarta Sans", system-ui',
          fontWeight: 700, fontSize: 15, letterSpacing: -0.2,
        }}>
          Nieuwe offerte <IcPlus size={16} color={P.red} />
        </button>
      </Section>
    </>
  );
};

const FotosTab = ({ item }) => {
  const P = window.PICO;
  return (
    <>
      <Section title="Foto's">
        <div style={{ marginBottom: 14 }}>
          <HouseHeroSvg variant={item.thumb.tone} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[0, 1, 2, 3].map(i => (
            <div key={i} style={{
              aspectRatio: '1 / 1', background: P.bg, borderRadius: 10,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              border: `1px dashed ${P.border}`,
              color: P.muted, fontFamily: '"Plus Jakarta Sans", system-ui',
              fontSize: 12, textAlign: 'center', padding: 8,
            }}>
              {i === 0 ? 'Meterkast' : i === 1 ? 'CV ruimte' : i === 2 ? 'Dak' : 'Gevel'}
            </div>
          ))}
        </div>
      </Section>
      <button style={{
        width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center',
        gap: 8, padding: '14px', background: 'none',
        border: `1px solid ${P.red}`, borderRadius: 10, cursor: 'pointer',
        color: P.red, fontFamily: '"Plus Jakarta Sans", system-ui',
        fontWeight: 700, fontSize: 15, letterSpacing: -0.2,
        marginBottom: 14,
      }}>
        Foto toevoegen <IcPlus size={16} color={P.red} />
      </button>
    </>
  );
};

const CommunicatieTab = ({ item }) => {
  const P = window.PICO;
  const messages = [
    { from: 'customer', name: item.customer, text: 'Hoi! Kunnen we de schouw verzetten naar donderdag?', time: '09:12' },
    { from: 'me', name: 'Jij', text: 'Dag, donderdag 10:00 kan. Stuur ik een nieuwe uitnodiging.', time: '09:34' },
    { from: 'customer', name: item.customer, text: 'Super, bedankt!', time: '09:35' },
  ];
  return (
    <Section title="Communicatie">
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 14 }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            display: 'flex', flexDirection: 'column',
            alignItems: m.from === 'me' ? 'flex-end' : 'flex-start',
          }}>
            <div style={{
              maxWidth: '80%',
              padding: '10px 14px', borderRadius: 14,
              background: m.from === 'me' ? P.ink : P.bg,
              color: m.from === 'me' ? '#fff' : P.ink,
              fontFamily: '"Plus Jakarta Sans", system-ui', fontSize: 14.5,
              letterSpacing: -0.15, lineHeight: 1.4,
              borderBottomRightRadius: m.from === 'me' ? 4 : 14,
              borderBottomLeftRadius: m.from === 'me' ? 14 : 4,
            }}>{m.text}</div>
            <div style={{
              fontFamily: '"Plus Jakarta Sans", system-ui', fontSize: 12,
              color: P.muted, marginTop: 4,
            }}>{m.name} · {m.time}</div>
          </div>
        ))}
      </div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        background: P.bg, borderRadius: 10, padding: '10px 12px',
        border: `1px solid ${P.border}`,
      }}>
        <input
          placeholder="Bericht schrijven…"
          style={{
            flex: 1, border: 'none', outline: 'none', background: 'transparent',
            fontFamily: '"Plus Jakarta Sans", system-ui', fontSize: 14.5,
            color: P.ink, letterSpacing: -0.15,
          }}
        />
        <button style={{
          border: 'none', background: P.red, color: '#fff',
          padding: '8px 14px', borderRadius: 8, cursor: 'pointer',
          fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 700, fontSize: 14,
        }}>Sturen</button>
      </div>
    </Section>
  );
};

const DetailView = ({ item, onBack, onStatusChange }) => {
  const P = window.PICO;
  const [mainTab, setMainTab] = React.useState('info');   // info | activiteit
  const [subTab, setSubTab] = React.useState('overzicht'); // overzicht | foto | comm

  // Read current status from mutable state (we'll allow change via dropdown)
  const [status, setStatus] = React.useState(item.status);
  React.useEffect(() => { setStatus(item.status); }, [item.id]);

  // Load Chapter chatbot widget only while the detail view is mounted.
  // Widget is a floating launcher in document.body; we snapshot children
  // before init and remove everything the widget added on unmount.
  React.useEffect(() => {
    const SCRIPT_ID = 'chapter-chatbot-script';
    const WIDGET_ID = 'sa30bp9omghqfy6gu2e60732';
    const before = new Set(Array.from(document.body.children));

    const initWidget = () => {
      try { window?.ChapterAI?.init?.(WIDGET_ID); } catch (e) {}
    };

    let script = document.getElementById(SCRIPT_ID);
    if (!script) {
      script = document.createElement('script');
      script.id = SCRIPT_ID;
      script.async = true;
      script.defer = true;
      script.crossOrigin = 'anonymous';
      script.src = 'https://cdn.chapter.works/chatbot-widget/chapter-chatbot-widget.js';
      script.onload = initWidget;
      document.head.appendChild(script);
    } else {
      initWidget();
    }

    return () => {
      Array.from(document.body.children).forEach(el => {
        if (!before.has(el)) el.remove();
      });
    };
  }, []);

  const iconCatMap = {
    generic: <IcPersonChat size={20} color={P.inkSoft} />,
    heatpump: <IcHeatPump size={20} color={P.inkSoft} />,
    solar: <IcSolar size={20} color={P.inkSoft} />,
  };

  return (
    <div style={{ background: P.bg, minHeight: '100%', paddingBottom: 30 }}>
      {/* Top bar with back + id + tabs */}
      <div style={{ background: '#fff', paddingBottom: 0 }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '16px 20px 10px', position: 'relative',
        }}>
          <button
            onClick={onBack}
            style={{
              background: 'none', border: 'none', padding: 8, cursor: 'pointer',
              marginLeft: -8, display: 'flex', alignItems: 'center',
            }}>
            <IcBack size={24} color={P.muted} />
          </button>
          <div style={{
            position: 'absolute', left: '50%', transform: 'translateX(-50%)',
            fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 800,
            fontSize: 19, color: P.ink, letterSpacing: -0.3,
          }}>#{item.id}</div>
          <div style={{ width: 24 }} />
        </div>

        {/* Main tabs: Info / Activiteit */}
        <div style={{ display: 'flex', borderBottom: `1px solid ${P.borderSoft}`, position: 'relative' }}>
          {['info', 'activiteit'].map(t => (
            <button
              key={t}
              onClick={() => setMainTab(t)}
              style={{
                flex: 1, padding: '14px 0', background: 'none', border: 'none',
                cursor: 'pointer',
                fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 600,
                fontSize: 16, letterSpacing: -0.2,
                color: mainTab === t ? P.ink : P.muted,
                position: 'relative',
              }}>
              {t === 'info' ? 'Info' : 'Activiteit'}
              {mainTab === t && (
                <div style={{
                  position: 'absolute', bottom: -1, left: '50%', transform: 'translateX(-50%)',
                  width: 'calc(100% - 40px)', height: 2.5, background: P.red,
                  borderRadius: 2,
                }} />
              )}
            </button>
          ))}
        </div>
      </div>

      {mainTab === 'activiteit' && (
        <div style={{
          padding: '80px 20px', textAlign: 'center',
        }}>
          <div style={{
            width: 64, height: 64, borderRadius: '50%', background: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            margin: '0 auto 16px',
            border: `1px solid ${P.border}`,
          }}>
            <IcDots size={28} color={P.muted} />
          </div>
          <h3 style={{
            fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 800,
            fontSize: 18, color: P.ink, letterSpacing: -0.3, margin: '0 0 6px',
          }}>Nog geen activiteit</h3>
          <p style={{
            fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 400,
            fontSize: 14, color: P.muted, letterSpacing: -0.1, margin: 0,
            lineHeight: 1.5,
          }}>
            Zodra er iets met deze opdracht gebeurt, vind je het hier terug.
          </p>
        </div>
      )}

      {mainTab === 'info' && (
        <div style={{ padding: '16px 16px 0' }}>
          {/* Category/partner row */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '4px 2px 10px',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {iconCatMap[item.category.icon]}
              <span style={{
                fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 500,
                fontSize: 15, color: P.inkSoft, letterSpacing: -0.2,
              }}>{item.category.label}</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <IcHeart size={18} color={P.red} style={{ fill: P.red, stroke: P.red }} />
              <span style={{
                fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 500,
                fontSize: 15, color: P.inkSoft, letterSpacing: -0.2,
              }}>{item.partner}</span>
            </div>
          </div>

          {/* Address */}
          <h2 style={{
            fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 800,
            fontSize: 24, color: P.ink, letterSpacing: -0.6, margin: '6px 0 0',
            textDecoration: 'underline', textDecorationColor: 'rgba(14,31,59,0.25)',
            textUnderlineOffset: 4,
            lineHeight: 1.2,
          }}>
            {item.address}, {item.postcode} {item.city}
          </h2>
          <button style={{
            background: 'none', border: 'none', padding: 0, cursor: 'pointer',
            color: P.red, fontFamily: '"Plus Jakarta Sans", system-ui',
            fontWeight: 700, fontSize: 15, letterSpacing: -0.2,
            marginTop: 8, display: 'inline-flex', alignItems: 'center', gap: 4,
          }}>
            Klantprofiel <IcChevR size={16} color={P.red} />
          </button>

          {/* Opdracht status row */}
          <div style={{
            background: '#fff', borderRadius: 12, padding: '14px 16px',
            marginTop: 16, marginBottom: 14,
            border: `1px solid ${P.border}`,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            <span style={{
              fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 500,
              fontSize: 15, color: P.inkSoft, letterSpacing: -0.2,
            }}>Opdracht status</span>
            <StatusDropdown status={status} onChange={(s) => { setStatus(s); onStatusChange && onStatusChange(s); }} />
          </div>

          {/* Sub-tabs: Overzicht / Foto's / Communicatie */}
          <div style={{
            display: 'flex', gap: 20,
            borderBottom: `1px solid ${P.borderSoft}`,
            marginBottom: 16, padding: '0 2px',
          }}>
            {[
              { key: 'overzicht', label: 'Overzicht' },
              { key: 'foto', label: "Foto's" },
              { key: 'comm', label: 'Communicatie', badge: item.unread },
            ].map(t => (
              <button
                key={t.key}
                onClick={() => setSubTab(t.key)}
                style={{
                  padding: '10px 0', background: 'none', border: 'none', cursor: 'pointer',
                  fontFamily: '"Plus Jakarta Sans", system-ui', fontWeight: 600,
                  fontSize: 15.5, letterSpacing: -0.2,
                  color: subTab === t.key ? P.ink : P.muted,
                  position: 'relative',
                  display: 'flex', alignItems: 'center', gap: 6,
                }}>
                {t.label}
                {t.badge > 0 && (
                  <span style={{
                    background: P.red, color: '#fff',
                    width: 18, height: 18, borderRadius: '50%',
                    fontSize: 11, fontWeight: 700,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{t.badge}</span>
                )}
                {subTab === t.key && (
                  <div style={{
                    position: 'absolute', bottom: -1, left: 0,
                    width: '100%', height: 2.5, background: P.red,
                    borderRadius: 2,
                  }} />
                )}
              </button>
            ))}
          </div>

          {subTab === 'overzicht' && <OverzichtTab item={item} onStatusChange={setStatus} />}
          {subTab === 'foto' && <FotosTab item={item} />}
          {subTab === 'comm' && <CommunicatieTab item={item} />}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { DetailView });
