// Messages + Activity Report — owner/sitter chat thread with photo updates,
// walk reports, scheduled visit reference.

const photoBG = window.photoBG;

function MessagesPage({ mode = 'thread' }) {
  return (
    <div style={{
      width:'100%',minHeight:'100%',background:'var(--c-bg)',
      color:'#2E2418',fontFamily:'var(--font-jp)',
    }}>
      <header style={{
        display:'flex',alignItems:'center',gap:16,padding:'16px 32px',
        background:'#fff',borderBottom:'1px solid rgba(0,0,0,.04)',
      }}>
        <img src="assets/logo-horizontal.png" alt="palpet" style={{height:40}}/>
        <div style={{flex:1}}/>
        <button style={iconBtn2}><Icons.Bell size={18}/></button>
        <div style={{
          width:36,height:36,borderRadius:'50%',
          background:'var(--c-primary-soft)',color:'var(--c-primary-deep)',
          display:'grid',placeItems:'center',fontWeight:700,fontSize:13,
        }}>Y</div>
      </header>

      <div style={{display:'grid',gridTemplateColumns:'320px 1fr 360px'}}>
        <ChatList/>
        <ChatThread/>
        <BookingRail/>
      </div>
    </div>
  );
}

const iconBtn2 = {
  width:38,height:38,borderRadius:12,border:'none',background:'transparent',
  cursor:'pointer',display:'grid',placeItems:'center',color:'#5d4d3a',
};

function ChatList() {
  const convs = [
    {id:1, name:'みかこさん', last:'お写真3枚お送りしました！とても元気でした 🐕', time:'15:42', unread:0, active:true, photo:'peach'},
    {id:2, name:'たくみさん', last:'お疲れさまでした。次回もぜひお願いします！', time:'昨日', unread:0, active:false, photo:'warm'},
    {id:3, name:'ゆりさん', last:'ご依頼ありがとうございます。日程について...', time:'5/18', unread:2, active:false, photo:'sage'},
    {id:4, name:'けんとさん', last:'メッセージありがとうございます', time:'5/15', unread:0, active:false, photo:'cream'},
  ];
  return (
    <aside style={{borderRight:'1px solid rgba(0,0,0,.04)',background:'#fff',height:'100%'}}>
      <div style={{padding:'24px 22px 12px'}}>
        <h2 style={{fontSize:20,fontWeight:700,marginBottom:14}}>メッセージ</h2>
        <div style={{
          background:'var(--c-bg)',borderRadius:12,padding:'10px 14px',
          display:'flex',gap:10,alignItems:'center',fontSize:13,
        }}>
          <Icons.Search size={16}/>
          <span style={{color:'#9c8a72'}}>シッターを検索</span>
        </div>
      </div>
      <div style={{display:'flex',flexDirection:'column'}}>
        {convs.map((c,i)=>(
          <button key={i} style={{
            display:'flex',gap:14,padding:'16px 22px',cursor:'pointer',
            background: c.active?'var(--c-primary-soft)':'transparent',
            border:'none',fontFamily:'inherit',textAlign:'left',
            borderLeft: c.active?'3px solid var(--c-primary)':'3px solid transparent',
          }}>
            <div style={{
              width:46,height:46,borderRadius:'50%',flex:'0 0 auto',
              background:photoBG(c.id),
            }}/>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:'flex',justifyContent:'space-between',gap:8,marginBottom:4}}>
                <strong style={{fontSize:14}}>{c.name}</strong>
                <span style={{fontSize:11,color:'#9c8a72'}}>{c.time}</span>
              </div>
              <div style={{fontSize:12,color:'#7a6a55',overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap'}}>
                {c.last}
              </div>
            </div>
            {c.unread > 0 && (
              <span style={{
                width:18,height:18,borderRadius:'50%',background:'var(--c-primary)',color:'#fff',
                fontSize:10,fontWeight:700,display:'grid',placeItems:'center',alignSelf:'center',flex:'0 0 auto',
              }}>{c.unread}</span>
            )}
          </button>
        ))}
      </div>
    </aside>
  );
}

function ChatThread() {
  return (
    <section style={{display:'flex',flexDirection:'column',height:'100%',background:'var(--c-bg)'}}>
      {/* Thread header */}
      <div style={{
        padding:'16px 28px',background:'#fff',borderBottom:'1px solid rgba(0,0,0,.04)',
        display:'flex',gap:14,alignItems:'center',
      }}>
        <div style={{width:42,height:42,borderRadius:'50%',background:photoBG('peach'),flex:'0 0 auto'}}/>
        <div style={{flex:1}}>
          <div style={{display:'flex',alignItems:'center',gap:6}}>
            <strong style={{fontSize:15}}>みかこさん</strong>
            <span style={{fontSize:10,padding:'2px 7px',borderRadius:999,background:'var(--c-primary-soft)',color:'var(--c-primary-deep)',fontWeight:700}}>✓ 本人確認</span>
          </div>
          <div style={{fontSize:12,color:'#7a6a55',marginTop:2,display:'flex',gap:4,alignItems:'center'}}>
            <span style={{width:8,height:8,borderRadius:'50%',background:'#94C9A0'}}/> 訪問中 ・ 散歩中
          </div>
        </div>
        <button style={iconBtn2}><Icons.Phone size={18}/></button>
        <button style={iconBtn2}><Icons.Cam size={18}/></button>
      </div>

      {/* Messages */}
      <div style={{flex:1,overflowY:'auto',padding:'24px 28px',display:'flex',flexDirection:'column',gap:14}}>
        <DateDivider label="5/24（土）"/>

        <Msg from="sitter" name="みかこ" time="9:55">
          おはようございます！ 5分後にお宅に到着予定です 🏠
        </Msg>
        <Msg from="me" time="9:56">
          おはようございます！よろしくお願いします 🙏
        </Msg>

        <ActivityCard title="お世話を開始しました" time="10:02"
                      type="start" detail="モカちゃん、しっぽふりながらお迎えに来てくれました ❤️"/>

        <Msg from="sitter" name="みかこ" time="10:18">
          ごはんを完食しました！お水もしっかり飲んでいます。
        </Msg>

        <PhotoMsg from="sitter" name="みかこ" time="10:22" tone="warm" caption="今、ごはんの後でうとうとしています 💤"/>

        <Msg from="me" time="10:23">
          ありがとうございます！普段通りで安心しました 😊
        </Msg>

        <ActivityCard title="お散歩を開始しました" time="11:10"
                      type="walk-start" detail="気温22℃ / 港区青山公園コース"/>

        <PhotoMsg from="sitter" name="みかこ" time="11:34" tone="sage" caption="芝生でちょっと休憩。木陰が気に入ったようです 🌳" route/>

        <ActivityCard title="お散歩が完了しました" time="11:48"
                      type="walk-end" stats={[
                        ['散歩距離','1.8 km'],['時間','38分'],['排泄','💩 1 / 💦 2'],
                      ]}/>

        <Msg from="sitter" name="みかこ" time="11:55">
          ちょうど良い運動量だったみたいで、今は満足げにくつろいでいます。<br/>
          あと5分ほどで予定時刻になります。お見送りで終了予定です！
        </Msg>

        <ActivityCard title="お世話が完了しました" time="12:00"
                      type="complete" detail="2時間のお預かりが完了しました。ありがとうございました。"/>
      </div>

      {/* Composer */}
      <div style={{
        padding:'14px 28px 22px',background:'#fff',borderTop:'1px solid rgba(0,0,0,.04)',
      }}>
        <div style={{display:'flex',gap:10,alignItems:'center'}}>
          <button style={iconBtn2}><Icons.Plus size={20}/></button>
          <button style={iconBtn2}><Icons.Cam size={20}/></button>
          <div style={{
            flex:1,background:'var(--c-bg)',borderRadius:14,padding:'12px 16px',
            fontSize:14,color:'#9c8a72',
          }}>メッセージを入力...</div>
          <button style={{
            background:'var(--c-primary)',color:'#fff',border:'none',width:42,height:42,borderRadius:'50%',
            display:'grid',placeItems:'center',cursor:'pointer',
          }}><Icons.Arrow size={18}/></button>
        </div>
      </div>
    </section>
  );
}

const DateDivider = ({label}) => (
  <div style={{display:'flex',justifyContent:'center',margin:'4px 0'}}>
    <span style={{
      fontSize:11,padding:'4px 14px',borderRadius:999,
      background:'rgba(0,0,0,.06)',color:'#7a6a55',
    }}>{label}</span>
  </div>
);

const Msg = ({from, name, time, children}) => {
  const isMe = from === 'me';
  return (
    <div style={{
      display:'flex',gap:10,alignItems:'flex-end',
      alignSelf: isMe ? 'flex-end' : 'flex-start',
      maxWidth: '72%',
    }}>
      {!isMe && (
        <div style={{width:30,height:30,borderRadius:'50%',background:photoBG('peach'),flex:'0 0 auto',marginBottom:18}}/>
      )}
      <div style={{display:'flex',flexDirection:'column',gap:4,minWidth:0}}>
        {!isMe && name && <div style={{fontSize:11,color:'#7a6a55',paddingLeft:4}}>{name}さん</div>}
        <div style={{
          padding:'12px 16px',borderRadius:18,
          background: isMe ? 'var(--c-primary)' : '#fff',
          color: isMe ? '#fff' : '#2E2418',
          fontSize:14,lineHeight:1.7,
          borderBottomLeftRadius: isMe ? 18 : 6,
          borderBottomRightRadius: isMe ? 6 : 18,
        }}>{children}</div>
        <div style={{fontSize:10,color:'#9c8a72',paddingLeft:isMe?0:4,textAlign:isMe?'right':'left'}}>{time}{isMe && ' ・ 既読'}</div>
      </div>
    </div>
  );
};

const PhotoMsg = ({from, name, time, tone, caption, route}) => {
  const isMe = from === 'me';
  return (
    <div style={{display:'flex',gap:10,alignItems:'flex-end',alignSelf:isMe?'flex-end':'flex-start',maxWidth:'72%'}}>
      {!isMe && <div style={{width:30,height:30,borderRadius:'50%',background:photoBG('peach'),flex:'0 0 auto',marginBottom:18}}/>}
      <div style={{display:'flex',flexDirection:'column',gap:4,minWidth:0}}>
        {!isMe && name && <div style={{fontSize:11,color:'#7a6a55',paddingLeft:4}}>{name}さん</div>}
        <div style={{
          background:'#fff',borderRadius:18,overflow:'hidden',
          borderBottomLeftRadius: isMe ? 18 : 6,
          width:280,
        }}>
          <div style={{aspectRatio: route?'5/3':'4/3', background:photoBG(tone), position:'relative'}}>
            {route && (
              <svg viewBox="0 0 280 168" style={{position:'absolute',inset:0,width:'100%',height:'100%'}}>
                <path d="M20,140 C 60,100 90,130 120,90 S 200,60 260,30" fill="none" stroke="#fff" strokeWidth="4" strokeLinecap="round" strokeDasharray="2 8"/>
                <circle cx="20" cy="140" r="6" fill="#fff"/>
                <circle cx="260" cy="30" r="6" fill="#fff"/>
              </svg>
            )}
          </div>
          {caption && <div style={{padding:'10px 14px',fontSize:13,lineHeight:1.6,color:'#3c2f1e'}}>{caption}</div>}
        </div>
        <div style={{fontSize:10,color:'#9c8a72',paddingLeft:4}}>{time}</div>
      </div>
    </div>
  );
};

const ActivityCard = ({title, time, type, detail, stats}) => {
  const colorMap = {
    'start':['var(--c-primary-soft)','var(--c-primary-deep)'],
    'walk-start':['#D9ECDC','#5E9C6C'],
    'walk-end':['#D9ECDC','#5E9C6C'],
    'complete':['#FBE9B8','#C8973A'],
  };
  const iconMap = {
    'start':Icons.Heart,'walk-start':Icons.Sparkle,
    'walk-end':Icons.Check,'complete':Icons.Star,
  };
  const [bg,fg] = colorMap[type] || ['var(--c-bg-alt)','#7a6a55'];
  const I = iconMap[type] || Icons.Sparkle;
  return (
    <div style={{
      alignSelf:'center',width:'100%',maxWidth:480,
      background:'#fff',borderRadius:18,padding:20,
      border:'1.5px solid '+bg,
    }}>
      <div style={{display:'flex',gap:12,alignItems:'center'}}>
        <div style={{
          width:40,height:40,borderRadius:12,flex:'0 0 auto',
          background:bg,color:fg,display:'grid',placeItems:'center',
        }}><I size={20} stroke={2.2}/></div>
        <div style={{flex:1}}>
          <strong style={{fontSize:14}}>{title}</strong>
          <div style={{fontSize:11,color:'#9c8a72',marginTop:2}}>{time}</div>
        </div>
      </div>
      {detail && <div style={{fontSize:13,lineHeight:1.7,color:'#5d4d3a',marginTop:12,paddingLeft:52}}>{detail}</div>}
      {stats && (
        <div style={{display:'grid',gridTemplateColumns:`repeat(${stats.length},1fr)`,gap:8,marginTop:14,paddingTop:14,borderTop:'1px solid rgba(0,0,0,.06)'}}>
          {stats.map(([k,v],i)=>(
            <div key={i} style={{textAlign:'center'}}>
              <div style={{fontSize:11,color:'#9c8a72'}}>{k}</div>
              <div style={{fontSize:16,fontWeight:700,marginTop:2}}>{v}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

function BookingRail() {
  return (
    <aside style={{borderLeft:'1px solid rgba(0,0,0,.04)',background:'#fff',padding:'24px 22px',overflowY:'auto'}}>
      <div style={{fontSize:12,color:'#9c8a72',fontWeight:600,letterSpacing:'.04em',marginBottom:6}}>NOW HAPPENING</div>
      <h3 style={{fontSize:18,fontWeight:700,marginBottom:16}}>進行中の依頼</h3>
      <div style={{
        background:'var(--c-bg)',borderRadius:18,padding:16,marginBottom:18,
        border:'1.5px solid var(--c-primary)',
      }}>
        <div style={{
          fontSize:11,fontWeight:700,color:'var(--c-primary-deep)',
          padding:'4px 10px',borderRadius:999,background:'var(--c-primary-soft)',
          display:'inline-flex',alignItems:'center',gap:6,marginBottom:10,
        }}><span style={{width:6,height:6,borderRadius:'50%',background:'var(--c-primary-deep)'}}/> 訪問中</div>
        <div style={{fontSize:14,fontWeight:700}}>モカちゃんのお世話</div>
        <div style={{fontSize:12,color:'#7a6a55',marginTop:4}}>5/24（土）10:00 〜 12:00</div>
        <div style={{height:6,background:'rgba(0,0,0,.06)',borderRadius:999,marginTop:14}}>
          <div style={{width:'80%',height:'100%',background:'var(--c-primary)',borderRadius:999}}/>
        </div>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:11,color:'#7a6a55',marginTop:6}}>
          <span>残り 約24分</span>
          <span style={{fontWeight:700,color:'var(--c-primary-deep)'}}>80%</span>
        </div>
      </div>

      <h4 style={{fontSize:13,fontWeight:700,marginTop:24,marginBottom:10,color:'#3c2f1e'}}>今日のレポート</h4>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,marginBottom:18}}>
        {[
          ['🍚','食事','完食'],
          ['🚶','散歩','1.8 km'],
          ['💧','水','3 / 5 回'],
          ['💩','排泄','正常'],
        ].map(([e,k,v],i)=>(
          <div key={i} style={{padding:12,background:'var(--c-bg)',borderRadius:12}}>
            <div style={{fontSize:18}}>{e}</div>
            <div style={{fontSize:11,color:'#9c8a72',marginTop:6}}>{k}</div>
            <div style={{fontSize:14,fontWeight:700,marginTop:2}}>{v}</div>
          </div>
        ))}
      </div>

      <h4 style={{fontSize:13,fontWeight:700,marginTop:24,marginBottom:10,color:'#3c2f1e'}}>今日のお写真</h4>
      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:6}}>
        {['peach','warm','sage','cream','peach','warm'].map((t,i)=>(
          <div key={i} style={{aspectRatio:'1/1',borderRadius:10,background:photoBG(t)}}/>
        ))}
      </div>
      <a style={{display:'block',marginTop:10,fontSize:12,fontWeight:600,color:'var(--c-primary-deep)',textAlign:'center'}}>すべての写真を見る →</a>

      <div style={{
        marginTop:24,padding:'14px 16px',background:'var(--c-bg)',borderRadius:14,
        fontSize:12,color:'#7a6a55',lineHeight:1.7,
      }}>
        <strong style={{color:'#3c2f1e'}}>緊急時の連絡先</strong><br/>
        <a style={{color:'var(--c-primary-deep)',fontWeight:600}}>パルペットサポート（24h）</a><br/>
        青山どうぶつ病院・03-XXXX-XXXX
      </div>
    </aside>
  );
}

window.MessagesPage = MessagesPage;
