/* Construction Journey — goal selection + 8-step survey + Project Team + Progress Center */
(function () {
  const { useState } = React;
  const Icon = window.Icon, PageHead = window.PageHead, Donut = window.Donut, Avatar = window.Avatar;
  const D = window.YEIDA, fmt = D.fmtINR;

  function MyJourney({ go, toast }) {
    const [tab, setTab] = useState('journey');
    return (
      <div>
        <PageHead title="My Construction Journey" subtitle="A guided, step-by-step path for your plot — from goal to completion certificate">
          <button className="btn btn-outline" onClick={() => go('sampleplans')}><Icon name="grid" size={17} />Design Explorer</button>
          <button className="btn btn-primary" onClick={() => go('construction')}><Icon name="construction" size={17} />Construction Module</button>
        </PageHead>

        {/* sub-tabs */}
        <div className="row gap-2" style={{ marginBottom: 22, borderBottom: '1px solid var(--line)', flexWrap: 'wrap' }}>
          {[['journey', 'Journey Steps'], ['team', 'Project Team'], ['progress', 'Progress Center']].map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{ padding: '11px 4px', marginRight: 22, background: 'none', border: 'none', borderBottom: '2.5px solid ' + (tab === k ? 'var(--blue-600)' : 'transparent'), color: tab === k ? 'var(--ink)' : 'var(--muted)', fontWeight: tab === k ? 700 : 500, fontSize: 14.5, cursor: 'pointer', marginBottom: -1 }}>{l}</button>
          ))}
        </div>

        {tab === 'journey' && <JourneySteps go={go} toast={toast} />}
        {tab === 'team' && <ProjectTeam toast={toast} />}
        {tab === 'progress' && <ProgressCenter />}
      </div>
    );
  }

  /* ---------------- GOAL SELECTION + 8-STEP ACCORDION SURVEY ---------------- */
  function JourneySteps({ go, toast }) {
    const [goal, setGoal] = useState('start');
    const [steps, setSteps] = useState(D.journeySteps);
    const [open, setOpen] = useState(() => {
      const a = D.journeySteps.findIndex(s => s.active);
      return a >= 0 ? a : 0;
    });

    const doneCount = steps.filter(s => s.done).length;
    const save = (i) => {
      setSteps(arr => arr.map((s, j) => j === i ? { ...s, done: true, active: false } : s));
      toast && toast('Information saved · ' + steps[i].title);
      const next = steps.findIndex((s, j) => j > i && !s.done);
      setOpen(next >= 0 ? next : -1);
    };

    return (
      <div>
        {/* progress header */}
        <div className="card card-pad anim-fade-up" style={{ marginBottom: 20, display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
          <Donut value={Math.round(doneCount / steps.length * 100)} label={doneCount + '/' + steps.length} sub="steps done" size={104} color="var(--emerald-500)" />
          <div style={{ flex: 1, minWidth: 220 }}>
            <h3 style={{ fontSize: 19 }}>You're {Math.round(doneCount / steps.length * 100)}% through your journey</h3>
            <p className="muted" style={{ fontSize: 13.5, marginTop: 4 }}>Complete each step below — saved steps turn green and stay editable. We'll guide you to the next action.</p>
            <div className="row gap-2" style={{ marginTop: 12, flexWrap: 'wrap' }}>
              <span className="badge badge-green"><Icon name="check" size={12} />{doneCount} completed</span>
              <span className="badge badge-blue">{steps.length - doneCount} remaining</span>
            </div>
          </div>
        </div>

        {/* goal selection */}
        <div className="card card-pad anim-fade-up" style={{ marginBottom: 20 }}>
          <h3 style={{ fontSize: 18 }}>What would you like to do with your plot?</h3>
          <p className="muted" style={{ fontSize: 13.5, marginTop: 4, marginBottom: 16 }}>Pick a goal — we'll personalise your journey around it.</p>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(220px,1fr))', gap: 12 }}>
            {D.journeyGoals.map(gOpt => {
              const on = goal === gOpt.id;
              return (
                <button key={gOpt.id} onClick={() => setGoal(gOpt.id)} className="card-hover" style={{ textAlign: 'left', cursor: 'pointer', padding: '14px 15px', borderRadius: 13, border: '1.5px solid ' + (on ? 'var(--blue-400)' : 'var(--line)'), background: on ? 'var(--blue-50)' : '#fff', display: 'flex', gap: 12, alignItems: 'flex-start', boxShadow: on ? '0 0 0 4px rgba(38,112,230,.1)' : 'none' }}>
                  <span style={{ width: 40, height: 40, borderRadius: 11, flex: 'none', display: 'grid', placeItems: 'center', background: on ? 'var(--blue-500)' : 'var(--bg-2)', color: on ? '#fff' : 'var(--muted)' }}><Icon name={gOpt.icon} size={20} /></span>
                  <div>
                    <div style={{ fontWeight: 700, fontSize: 13.5, lineHeight: 1.25 }}>{gOpt.title}</div>
                    <div className="muted" style={{ fontSize: 11.5, marginTop: 3, lineHeight: 1.35 }}>{gOpt.desc}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* accordion survey */}
        <div className="col gap-3">
          {steps.map((s, i) => {
            const isOpen = open === i;
            const state = s.done ? 'done' : s.active || isOpen ? 'active' : 'todo';
            return (
              <div key={s.key} className="card anim-fade-up" style={{ overflow: 'hidden', border: '1px solid ' + (state === 'done' ? '#bfe6d3' : isOpen ? 'var(--blue-200,#bcd0f5)' : 'var(--line)'), borderLeft: '4px solid ' + (state === 'done' ? 'var(--emerald-500)' : state === 'active' ? 'var(--blue-500)' : 'var(--line)') }}>
                {/* header row */}
                <button onClick={() => setOpen(isOpen ? -1 : i)} style={{ width: '100%', display: 'flex', alignItems: 'center', gap: 14, padding: '15px 18px', background: s.done ? 'var(--emerald-50)' : '#fff', border: 'none', cursor: 'pointer', textAlign: 'left' }}>
                  <span style={{ width: 38, height: 38, borderRadius: 99, flex: 'none', display: 'grid', placeItems: 'center', fontWeight: 800, fontFamily: 'var(--font-display)', fontSize: 15, background: s.done ? 'var(--emerald-500)' : state === 'active' ? 'var(--blue-500)' : 'var(--bg-2)', color: s.done || state === 'active' ? '#fff' : 'var(--faint)' }}>
                    {s.done ? <Icon name="check" size={18} /> : i + 1}
                  </span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="row gap-2" style={{ flexWrap: 'wrap' }}>
                      <span style={{ fontWeight: 700, fontSize: 15 }}>{s.title}</span>
                      {s.done && <span className="badge badge-green" style={{ fontSize: 10.5 }}><Icon name="check" size={11} />Information Saved</span>}
                      {state === 'active' && !s.done && <span className="badge badge-blue" style={{ fontSize: 10.5 }}>In progress</span>}
                    </div>
                    <div className="muted" style={{ fontSize: 12.5, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.done ? s.summary : s.desc}</div>
                  </div>
                  <Icon name={isOpen ? 'chevU' : 'chevD'} size={18} style={{ color: 'var(--faint)', flex: 'none' }} />
                </button>

                {/* body */}
                {isOpen && (
                  <div className="anim-fade-in" style={{ padding: '4px 18px 18px 70px', borderTop: '1px solid var(--line-2)' }}>
                    <StepBody step={s} go={go} />
                    <div className="row gap-3" style={{ marginTop: 16 }}>
                      <button className="btn btn-primary btn-sm" onClick={() => save(i)}><Icon name="check" size={15} />{s.done ? 'Update & Save' : 'Save & Continue'}</button>
                      {s.done && <span className="row gap-2 faint" style={{ fontSize: 12.5 }}><Icon name="edit" size={14} />Editable anytime</span>}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  function StepBody({ step, go }) {
    // tailored, lightweight content per step
    switch (step.key) {
      case 'goal':
        return <Note>Your selected goal drives the recommended steps, designs and budget. You can change it from the selector above.</Note>;
      case 'plot':
        return (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(150px,1fr))', gap: 12 }}>
            {[['Allotment No.', D.user.allotment], ['Plot', D.user.plot], ['Sector', D.user.sector], ['Pocket', D.user.pocket]].map(([l, v]) => <Field key={l} label={l} value={v} />)}
          </div>
        );
      case 'design':
        return (
          <div>
            <Note>Selected design from the Design Explorer. Browse alternatives anytime.</Note>
            <button className="btn btn-outline btn-sm" style={{ marginTop: 10 }} onClick={() => go('sampleplans')}><Icon name="grid" size={15} />Open Design Explorer</button>
          </div>
        );
      case 'planning':
        return (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(150px,1fr))', gap: 12 }}>
            {[['Configuration', 'G+1'], ['Built-up area', '4,200 sq.ft'], ['Est. duration', '11 months'], ['Plan status', 'Sanctioned']].map(([l, v]) => <Field key={l} label={l} value={v} />)}
          </div>
        );
      case 'budget':
        return (
          <div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(150px,1fr))', gap: 12, marginBottom: 12 }}>
              {[['Total budget', fmt(D.construction.estimatedCost)], ['Milestones', '5'], ['Funded', fmt(D.construction.spent)]].map(([l, v]) => <Field key={l} label={l} value={v} />)}
            </div>
            <button className="btn btn-outline btn-sm" onClick={() => go('payments')}><Icon name="rupee" size={15} />Set up milestone payments</button>
          </div>
        );
      case 'contractor':
        return (
          <div>
            <Note>Assign your project team — manager, site engineer, architect & crew. View the Project Team tab to manage contacts.</Note>
          </div>
        );
      case 'progress':
        return <Note>Once construction starts, track every stage with photos, notes and dates in the Progress Center.</Note>;
      case 'certificate':
        return <Note>After final inspection, apply for and download your Completion Certificate here.</Note>;
      default:
        return null;
    }
  }

  function Field({ label, value }) {
    return (
      <div style={{ background: 'var(--bg)', borderRadius: 11, padding: '11px 14px' }}>
        <div className="faint" style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em' }}>{label}</div>
        <div style={{ fontWeight: 700, fontSize: 14.5, marginTop: 3 }}>{value}</div>
      </div>
    );
  }
  function Note({ children }) {
    return <p className="muted" style={{ fontSize: 13.5, lineHeight: 1.6 }}>{children}</p>;
  }

  /* ---------------- PROJECT TEAM ---------------- */
  function ProjectTeam({ toast }) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 18 }}>
        <div className="anim-fade-up">
          <h3 style={{ fontSize: 18, marginBottom: 14 }}>Your Project Team</h3>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            {D.projectTeam.map(m => (
              <div key={m.role} className="card card-pad card-hover">
                <div className="row spread" style={{ marginBottom: 12 }}>
                  <div style={{ position: 'relative' }}>
                    <Avatar initials={m.avatar} size={46} />
                    {m.online && <span style={{ position: 'absolute', bottom: 0, right: 0, width: 12, height: 12, borderRadius: 99, background: 'var(--emerald-500)', border: '2px solid #fff' }} />}
                  </div>
                  <span className="badge badge-navy" style={{ fontSize: 10.5 }}>{m.role}</span>
                </div>
                <div style={{ fontWeight: 700, fontSize: 15 }}>{m.name}</div>
                <div className="muted" style={{ fontSize: 12.5, marginTop: 1 }}>{m.org}</div>
                <div className="row gap-2" style={{ marginTop: 12 }}>
                  <button className="btn btn-outline btn-sm" style={{ flex: 1 }} onClick={() => toast && toast('Calling ' + m.name)}><Icon name="phone" size={14} />Call</button>
                  <button className="btn btn-ghost btn-sm" style={{ border: '1px solid var(--line)', flex: 1 }} onClick={() => toast && toast('Message sent')}><Icon name="chat" size={14} />Message</button>
                </div>
              </div>
            ))}
          </div>
        </div>
        {/* team updates / milestone */}
        <div className="card card-pad anim-fade-up" style={{ animationDelay: '.06s', alignSelf: 'start' }}>
          <h3 style={{ fontSize: 17, marginBottom: 16 }}>Team Updates</h3>
          <div style={{ position: 'relative' }}>
            {D.teamUpdates.map((u, i, arr) => (
              <div key={i} className="row" style={{ alignItems: 'flex-start', gap: 12, paddingBottom: i === arr.length - 1 ? 0 : 16, position: 'relative' }}>
                {i !== arr.length - 1 && <span style={{ position: 'absolute', left: 16, top: 36, bottom: 0, width: 2, background: 'var(--line)' }} />}
                <Avatar initials={u.avatar} size={34} />
                <div style={{ paddingTop: 1 }}>
                  <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.45 }}><b style={{ color: 'var(--ink)' }}>{u.who}</b> — {u.text}</div>
                  <div className="faint" style={{ fontSize: 11.5, marginTop: 3 }}>{u.time}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  /* ---------------- PROGRESS CENTER (stages + live view) ---------------- */
  function ProgressCenter() {
    const overall = Math.round(D.progressStages.reduce((s, x) => s + x.pct, 0) / D.progressStages.length);
    return (
      <div>
        {/* live view + summary */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18, marginBottom: 22 }}>
          <div className="card anim-fade-up" style={{ overflow: 'hidden' }}>
            <div style={{ position: 'relative', height: 280, background: 'radial-gradient(120% 120% at 50% 0%,#16407e,#081a39)', display: 'grid', placeItems: 'center' }}>
              <div style={{ position: 'absolute', inset: 0, opacity: .3, backgroundImage: 'linear-gradient(rgba(255,255,255,.06) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,.06) 1px,transparent 1px)', backgroundSize: '36px 36px' }} />
              <div style={{ position: 'absolute', top: 14, left: 14, display: 'flex', alignItems: 'center', gap: 7, padding: '6px 12px', borderRadius: 99, background: 'rgba(210,63,63,.92)', color: '#fff', fontSize: 12, fontWeight: 700 }}>
                <span style={{ width: 8, height: 8, borderRadius: 99, background: '#fff', animation: 'pulseDot 1.4s infinite' }} />LIVE
              </div>
              <div style={{ textAlign: 'center', color: '#fff', position: 'relative' }}>
                <div style={{ width: 70, height: 70, borderRadius: 99, margin: '0 auto 12px', display: 'grid', placeItems: 'center', background: 'rgba(255,255,255,.12)', border: '1px solid rgba(255,255,255,.25)' }}><Icon name="eye" size={32} /></div>
                <div style={{ fontWeight: 700, fontSize: 16 }}>Live Site Camera</div>
                <div style={{ fontSize: 12.5, color: 'rgba(200,216,240,.8)', marginTop: 4 }}>Plot B-47 · Cam 1 · 1080p — drop in your RTSP/webcam feed</div>
              </div>
            </div>
            <div className="row spread" style={{ padding: '12px 16px' }}>
              <div className="row gap-2">{['Cam 1', 'Cam 2', 'Drone'].map((c, i) => <span key={c} className={'chip' + (i === 0 ? ' active' : '')} style={{ fontSize: 12 }}>{c}</span>)}</div>
              <span className="faint" style={{ fontSize: 12 }}>Updated just now</span>
            </div>
          </div>
          <div className="card card-pad anim-fade-up" style={{ animationDelay: '.06s' }}>
            <div className="row center" style={{ margin: '6px 0 14px' }}><Donut value={overall} label={overall + '%'} sub="overall" color="var(--blue-500)" /></div>
            <div className="col gap-2">
              {[['Daily Site Photos', 'image', '42 this month'], ['Weekly Progress Report', 'documents', 'Latest: 06 Jun'], ['Current Stage', 'construction', 'Slab Casting']].map(([l, ic, v]) => (
                <div key={l} className="row spread" style={{ padding: '9px 0', borderBottom: '1px solid var(--line-2)' }}>
                  <span className="row gap-3" style={{ fontSize: 13, fontWeight: 600 }}><span style={{ width: 30, height: 30, borderRadius: 8, display: 'grid', placeItems: 'center', background: 'var(--blue-50)', color: 'var(--blue-600)' }}><Icon name={ic} size={15} /></span>{l}</span>
                  <span className="faint" style={{ fontSize: 12 }}>{v}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* stage timeline */}
        <div className="card card-pad anim-fade-up">
          <h3 style={{ fontSize: 18, marginBottom: 18 }}>Construction Stages</h3>
          <div style={{ position: 'relative' }}>
            {D.progressStages.map((st, i, arr) => {
              const state = st.pct === 100 ? 'done' : st.pct > 0 ? 'active' : 'todo';
              const cc = state === 'done' ? 'var(--emerald-500)' : state === 'active' ? 'var(--blue-500)' : '#c2cedd';
              return (
                <div key={st.name} className="row" style={{ alignItems: 'flex-start', gap: 16, paddingBottom: i === arr.length - 1 ? 0 : 18, position: 'relative' }}>
                  {i !== arr.length - 1 && <span style={{ position: 'absolute', left: 17, top: 36, bottom: 0, width: 2, background: state === 'done' ? 'var(--emerald-500)' : 'var(--line)' }} />}
                  <span style={{ width: 36, height: 36, borderRadius: 99, flex: 'none', display: 'grid', placeItems: 'center', background: '#fff', border: '2.5px solid ' + cc, color: cc, zIndex: 1 }}>
                    {state === 'done' ? <Icon name="check" size={16} /> : state === 'active' ? <span style={{ width: 9, height: 9, borderRadius: 99, background: cc, animation: 'pulseDot 1.4s infinite' }} /> : <span style={{ fontWeight: 700, fontSize: 12 }}>{i + 1}</span>}
                  </span>
                  <div style={{ flex: 1, paddingTop: 4 }}>
                    <div className="row spread" style={{ flexWrap: 'wrap', gap: 8 }}>
                      <span style={{ fontWeight: 700, fontSize: 14.5, color: state === 'todo' ? 'var(--faint)' : 'var(--ink)' }}>{st.name}</span>
                      <div className="row gap-2">
                        {st.photos > 0 && <span className="badge badge-gray" style={{ fontSize: 10.5 }}><Icon name="image" size={11} />{st.photos}</span>}
                        <span className={'badge badge-' + (state === 'done' ? 'green' : state === 'active' ? 'blue' : 'gray')} style={{ fontSize: 10.5 }}>{state === 'done' ? 'Completed' : state === 'active' ? st.pct + '%' : 'Upcoming'}</span>
                      </div>
                    </div>
                    {st.note && <div className="muted" style={{ fontSize: 12.5, marginTop: 3 }}>{st.note}</div>}
                    <div className="faint" style={{ fontSize: 11.5, marginTop: 3 }}>{st.date}</div>
                    {state === 'active' && <div className="progress" style={{ height: 5, marginTop: 7, maxWidth: 320 }}><span style={{ width: st.pct + '%' }} /></div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  window.MyJourney = MyJourney;
})();
